Programming/SpringFramework

[Spring] 빈 (Bean)

잇나우 2020. 7. 31. 18:54
반응형

Bean

Bean은 IoC Container가 관리하는 객체를 말한다. 직접 new를해서 만든 인스턴스, 객체는 Bean이 아니다.

ExamController Example = new ExamController();

ExamController bean = applicationContext.getBean(ExamController.class);

위 예제 중 둘다 같은 객체는 맞지만 Example은 Bean이 아니고 아래 bean 객체만 Bean이다. 그 이유는 applicationContext가 관리하는 객체에서 가져온것이기 때문이다.
applicationContext에는 모든 Bean이 등록되어 있다. BeanFactory 인터페이스는 Container 자체라고 보면된다. 그래서 모든 Bean의 정보를 가지고 있는데 applicationContextBeanFactory를 상속받고 있어서 applicationContext도 모든 Bean 정보를 갖고 있다.

Bean을 등록하는 방법

Bean을 등록하는 방법은 크게 두가지가 있다.

  1. Component를 Scan을 하는 방법
    @Component를 붙여주면 Spring에서 자동으로 Bean으로 해당 객체를 등록한다.
    @Component와 비슷한 성격에 어노테이션들이 있는데 다음과 같다.

    -   @Repository
    -   @Service
    -   @Controller
    -   @Configuration

위 어노테이션들도 실질적으로 들어가면 @Component가 붙어있다.

  1. 직접 xml이나 자바 설정 파일에 Bean을 등록하는 방법
@Configuration  
public class SampleConfig {  

  @Bean  
  public SampleController sampleController() {  
  return new SampleController();  
  }  
}

xml 파일말고 자바 설정파일을 만들어 Bean을 등록한 예제이며 SampleController 메소드가 리턴하는 객체 자체가 Bean으로 등록이 된다.

반응형