-
Spring bean 정리(1)_bean 등록Spring Framework 2023. 8. 13. 15:43
Spring bean
- 스프링 ioc 컨테이너에 의해 관리되는 자바 객체
spring ioc container
- bean의 생명주기를 관리하고 추가적인 기능을 제공한다.
- 제어 흐름을 외부에서 관리(ioc)해주고 객체들 간의 의존 관계를 스프링 컨테이너가 런타임 과정에서 알아서 만들어 준다.
스프링 빈 등록 방식
- component scan
- @Component를 명시하여 빈을 추가하는 방법
- 개발자가 직접 컨트롤이 가능한 클래스들의 경우에 사용
- 클래스 위에 @Component를 붙이면 스프링이 알아서 spring container에 bean을 등록한다.
- @Component는 @Target(ElementType.TYPE) 설정이 있으므로 Class 혹은 Interface에만 붙일 수 있다.
- @Controller, @Service, @Repository, @Configuration은 아래와 같이 @Component 설정이 있어 스캔 대상이 된다.
// @Component와 @Controller 인터페이스 코드 @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Component { // code.. } @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Controller { // code.. } /* - @Controller : 스프링 MVC 컨트롤러로 인식된다. - @Repository : 스프링 데이터 접근 계층으로 인식하고 해당 계층에서 발생하는 예외는 모두 DataAccessException으로 변환한다. - @Service : 특별한 처리는 하지 않으나, 개발자들이 핵심 비즈니스 계층을 인식하는데 도움을 준다. - @Configuration : 스프링 설정 정보로 인식하고 스프링 빈이 싱글톤을 유지하도록 추가 처리를 한다. (물론 스프링 빈 스코프가 싱글톤이 아니라면 추가 처리를 하지 않음.) */- Java 코드를 이용한 등록
- @Bean을 사용한다.
- 개발자가 컨트롤이 불가능한 외부 라이브러리들을 Bean으로 등록하고 싶은 경우에 사용
- class를 생성하고 @Configuration을 활용한다.
- @Bean은 @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) 설정이 있어, 메소드나 어노테이션에만 붙일 수 있다.
// @Bean 코드 @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Bean { // code.. } // 예시 @Configuration public class SampleConfig { @Bean public SampleService sampleService() { // code.. } }- 수동 등록
- ApplicationContext를 호출하여 수동으로 설정 파일을 이용
public class Main { public static void main(String[] args) { final ApplicationContext beanFactory = new AnnotationConfigApplicationContext(AppConfig.class); final AppConfig bean = beanFactory.getBean("appConfig", AppConfig.class); } }출처)
'Spring Framework' 카테고리의 다른 글
Spring bean 정리(3)_Spring Bean 스코프 (0) 2023.08.13 Spring bean 정리(2)_Bean 생성과 singleton (0) 2023.08.13 spring MVC & servlet 정리 (0) 2023.08.13 spring 의존성 주입(DI) (0) 2023.08.11 spring 제어의 역전 (Ioc) (0) 2023.08.11