Spring Boot
스프링 Spring @Autowired? @Component? @Bean?차이
dev.mk
2023. 7. 16. 15:56
반응형
스프링 시큐리티를 설정하면서 @Autowired, @Bean, @Component어노테이션이 많이 보이는데
어떤건지 간단하게 정리해보자
SecurityConfig.java
@Configuration
@EnableWebSecurity
public class SecurityConfig{
// 권한이 없는 사용자 접근에 대한 handler
@Bean
CustomWebAccessDeniedHandler customWebAccessDeniedHandler() {
return new CustomWebAccessDeniedHandler();
}
// 인증되지 않은 사용자 접근에 대한 handler
@Autowired
private CustomWebAuthenticationEntryPoint customWebAuthenticationEntryPoint;
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf(csrf -> csrf.disable())
.exceptionHandling( exceptionHandling ->
exceptionHandling
.authenticationEntryPoint(customWebAuthenticationEntryPoint) // 인증되지 않은 사용자 접근 시
.accessDeniedHandler(customWebAccessDeniedHandler()) // 권한이 없는 사용자 접근 시
);
return httpSecurity.build();
}
}
이 설정파일에서
CustomWebAccessDeniedHandler는 @Bean으로 등록되어있고
CustomWebAuthenticationEntryPoint는 @Autowired으로 등록 되어있다.
둘다 @Bean으로 등록하나 @Autowired으로 의존성을 주입시키나 동작은 똑같다.
테스트를 위해 둘다 다르게 설정했다.
CustomWebAuthenticationEntryPoint파일의 내용을보면
CustomWebAuthenticationEntryPoint.java
@Slf4j
@Component
public class CustomWebAuthenticationEntryPoint implements AuthenticationEntryPoint{
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.sendRedirect("/error/403");
}
}
이 클래스에는 @Component 어노테이션이 있다.
@Component란? 개발자가 직접 작성한 Class 를 Bean 으로 만드는 것
다음으로 CustomWebAccessDeniedHandler 클래스를 보면
CustomWebAccessDeniedHandler.java
@Slf4j
public class CustomWebAccessDeniedHandler implements AccessDeniedHandler{
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.sendRedirect("/error/403");
}
}
@Component 어노테이션이 없는 대신 SecurityConfig.java에는 @Bean으로 등록되어 있다.
@Bean란? 개발자가 작성한 Method 를 통해 반환되는 객체를 Bean 으로 만드는것
@Autowired란? 스프링 컨테이너에 등록한 빈에게 의존관계주입이 필요할 때, DI(의존성 주입)을 도와주는 어노테이션
즉 위에서 @Component 클래스를 @Bean으로 만들고 그 빈의 대한 의존성을 주입시킨다.
반응형