신규 블로그를 만들었습니다!

2020년 이후부터는 아래 블로그에서 활동합니다.

댓글로 질문 주셔도 확인하기 어려울 수 있습니다.

>> https://bluemiv.tistory.com/

Java를 이용한 Bean 생성

보통 xml파일을 가지고 bean을 생성했지만, 

java파일을 이용해서도 bean을 생성할 수 있다.

 

어노테이션을 이용하는 방법이다.

 

@Configuration

@Bean

 

위 2개의 어노테이션을 이용하면 된다.

 

예를들어,

@Configuration // 컨테이너

public class ApplicationConfig{

~

~

}

 

@Bean // 빈

public Student student1(){

Student student = new Student("honkgu", 26);

return student;

}

 

 

 

코드 살펴보기

디렉토리 구조

 

ApplicationConfig.java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class ApplicationConfig {
 
    // 생성자 메소드를 이용한 빈 생성
    @Bean
    public Student student1() {
        Student student = new Student("hongku", 26);
        return student;
    }
    
    // setter 메소드를 이용한 빈 생성
    @Bean
    public Student student2() {
        Student student = new Student();
        student.setName("hongsoon");
        student.setAge(26);
        return student;
    }
}
​

 

Student.java

public class Student {
 
    private String name;
    private int age;
    
    // constructor
    public Student() {
        
    }
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
 
    // get set method
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }
    
}​

 

 

Main.java

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
public class Main {
 
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx
            = new AnnotationConfigApplicationContext(ApplicationConfig.class);
 
        Student student1 = ctx.getBean("student1", Student.class);
        System.out.println(student1.toString());
 
        Student student2 = ctx.getBean("student2", Student.class);
        System.out.println(student2.toString());
    }
}​

context를 만들때, AnnotationConfigApplicaitionContext를 사용한다.

 

 

 

※ 이 글은 Seoul Wiz - '실전 Spring 강좌'를 요약하여 작성하였습니다.

>> 유튜브 - SeoulWiz 

 

 

 

  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기