[TIL] 23.01.10 @Component 와 @Configuration 차이

hyewon jeong·2023년 1월 10일
0

TIL

목록 보기
66/138

1 . 문제점

스프링은 @ComponentScan은 서버 실행시 @Component 어노테이션 및 streotype(@Controller, @Servicie, @Repository)이 지정된 클래스들을 찾아 Bean으로 등록해주는 역할을 합니다.

근데 WebSecurityConfig 클래스를 작성하는 곳에는
@Configuration 으로 되어 있어 의문이 생김

2 . 시도한 점

@Component
@RequiredArgsConstructor
@EnableWebSecurity // 스프링 Security 지원을 가능하게 함
@EnableGlobalMethodSecurity(securedEnabled = true) // @Secured 어노테이션 활성화
public class WebSecurityConfig {
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

3 . 해결


@Configuration
@RequiredArgsConstructor
@EnableWebSecurity // 스프링 Security 지원을 가능하게 함
@EnableGlobalMethodSecurity(securedEnabled = true) // @Secured 어노테이션 활성화
public class WebSecurityConfig {
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        // h2-console 사용 및 resources 접근 허용 설정
        return (web) -> web.ignoring()
                .requestMatchers(PathRequest.toH2Console())
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations());
    }

4 . 알게 된점

Configuration의 API를 확인해보면 Streotype과 마찬가지로 @Component가 선언되어 있는 것을 확인할 수 있습니다.

@Configuration

@Component 와 @Configuration은 큰 차이는 없습니다.

위에서 보앗듯이, @Configuration의 내부를 살펴보면 @Component가 정의되어 있습니다. 따라서 @Component와 @Bean을 비교하는 것이 맞습니다.

우선적으로, 개발자가 직접 작성한 클래스에 대하여 @Component는 위와 같이 bean으로 등록 할 수 있습니다. 반대로 라이브러리 혹은 내장 클래스등 개발자가 직접 제어가 불가능한 클래스의 경우 @Configuration + @Bean 어노테이션을 이용하여 bean으로 등록하여 사용하면 됩니다.

👍 정리

@Component

  • 개발자가 직접 작성한 클래스를 bean 등록하고자 할 경우 사용

@Configuration + @Bean

  • 외부라이브러 또는 내장 클래스를 bean으로 등록하고자 할 경우 사용.

  • 1개 이상의 @Bean을 제공하는 클래스의 경우 반드시 @Configuraton을 명시

profile
개발자꿈나무

0개의 댓글