개발/Spring

[Spring] - 빈(Bean) 수동등록, 자동등록

dongdev 2021. 12. 28. 10:31

빈등록 방법은 크게 두가지로 나뉜다.

- 수동등록(@Bean)

- 자동등록(@Component, @Autowired)

 

 

- 수동등록(@Bean)

@Configuration 주석이 있는 클래스 안에다가 @Bean 주석으로 빈을 등록해준다.

 

 

- 자동등록(@Component, @Autowired)

@Configuration, @ComponentScan 만 추가하면 된다.

(패키지 상위에 생성되는 xxxApplication에 @SpringBootApplication엔 다 포함되어있다.)

 

@ComponentScan은 필터를 적용할 수 있다.

basePackages: 스캔을 시작할 장소 (default:프로젝트 전부)

includeFilters:  스캔을 추가로할 장소

excludeFilters:  스캔을 안할 장소

 

 

구현 클래스에 @Component 주석을 넣어 주면된다.

구현 클래스에 생성자로 다른 빈을 참조할 경우 @Autowired로 의존성 주입해준다. (필드주입)

 

 

 

참고) 같은이름의 빈이 수동등록, 자동등록으로 중복 등록되었다면 수동등록 빈이 우선순위를 가진다.