카테고리 없음

[Spring] bean을 스프링 컨테이너에 등록하는 방법

빠작 2023. 7. 26. 11:25

bean을 등록하는 방법은 2가지가 있다.

 

1. @component 어노테이션

빈으로 등록하고자 하는 클래스 위에 @component 어노테이션을 붙여주면 된다.

흔히 사용하는 @controller, @service, @repository 같은 어노테이션도 @component의 일종이다.

보통 사용자가 직접 생성한 객체를 등록하고 싶을 때 자주 사용한다.

 

2. @configuration, @bean 어노테이션

@configuration 어노테이션의 설명을 보면

Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime 라고 나와있는데, 즉 런타임 때 여러개의 bean을 생성하고 이들에 대한 요청을 처리할 수 있게 하는 클래스를 나타내는 어노테이션이다.

 

아래와 같이 클래스 위에 @component 를 붙여주고

클래스 내부에서 빈으로 등록할 객체에 @Bean 어노테이션을 붙여주면 된다. 

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

    @Bean
    public LoginExceptionHandler loginExceptionHandler(){
        return new LoginExceptionHandler();
    }

 

@comfiguration과 @bean을 이용하는 방식의 특징 2가지가 있는데,

1.직접 생성한 클래스가 아닌 외부 라이브러리를 bean으로 등록하고 싶을 때도 사용 가능하다

2. 빈 등록과 의존성 주입이 함께 일어난다.