[SpringBoot] 인터셉터에서 @AutoWired 작동 에러

박원종·2021년 8월 3일
0

SpringBoot

목록 보기
1/1

❓AuthInterceptor에서 AutoWired 가 안된다?

AuthInterceptor에서 Jwt 클래스를 의존 주입받고 있는데 자꾸만 null이 뜨고 심지어 @Value 어노테이션도 바인딩되지 않았다..

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Value("${token.header-name}")
    String header;
    
    @Autowired
    private Jwt jwt;  
    
     @Override
    public boolean preHandle(HttpServletRequest request,
    HttpServletResponse response, Object handler) throws Exception {
    	(생략)
    }
    (생략)
}

안그래도 얼마없는 머리털 쥐어뜯으며 고민하다가
정말 고마운 블로그를 하나 발견해서 공유하려고 한다.

https://eastglow.github.io/back-end/2019/08/01/Spring-Interceptor-%EC%82%AC%EC%9A%A9-%EC%8B%9C-%EC%9D%98%EC%A1%B4%EC%84%B1-%EC%A3%BC%EC%9E%85%EC%9D%B4-%EC%95%88%EB%90%98%EB%8A%94-%EA%B2%BD%EC%9A%B0.html

요약하면 이렇다

문제는 인터셉터를 등록하고 있는
WebMvcConfigurer 을 구현한 클래스에 있다!

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AuthInterceptor())
        	.addPathPatterns("/**");
    }
}

위 처럼 addInterceptor 메소드의 인자로 new AuthInterceptor()을 주면 spring에서 관리를 해주지 않는다고 한다.
그래서 빈으로 등록된 AuthInterceptor의 인스턴스를 인자로 주면 작동이 잘된다는 것이다.
아마, 이것을 해결할 수 있는 두가지의 방법이 있을 것 같은데

  1. WebMvcConfigurer을 구현한 클래스에서 인터셉터 등록과 빈등록을 한꺼번에 하기
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor()) // <--변경
        	.addPathPatterns("/**");
    }
    @Bean
    public AuthInterceptor authInterceptor(){
    	return new AuthInterceptor();
    }
}

이 코드를 사용하려면 AuthInterceptor의 @Component 태그는 없애줘야한다.
아니면 이미 빈이 만들어져있다고 오류를 내뿜을 것이다.

  1. 이미 빈으로 등록된 AuthInterceptor를 addInterceptor에 인자로 주기
@Configuration
public class InterceptorConfig implemets WebMvcConfigurer {
    @Autowired
    AuthInterceptor authInterceptor; // <--AuthInterceptor 인스턴스 받아오기
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(auth) // <--변경
        	.addPathPatterns("/**");
    }

}

이번에는 AuthInterceptor에 @Component 태그를 빠뜨리면 안된다!!
필자는 2번째 방법으로 문제를 해결하였다.

ps. 또 다른 문제로 애먹고 있는게 있는데...
내 컴퓨터가 이상한건지 WebMvcConfigurer로 addCorsMappings를 통해 cors 설정을 
전역적으로해주면 제대로 작동하지 않는 문제도 확인했는데... 이건 도통 뭐가 문젠지
모르겠다.... @CrossOrigin은 또 잘작동한다는것... 
스택오버플로우보면 나만 이런 에러를 당하는건 아닌것같은데...
내 주변을 보면 나만... 당하고 있다... 다들 잘쓰는데 왜 나만...?
스택오버플로우에도 해결책이 제시되어있지않아서...슬프다... 더 공부하다보면
알게될 것이라고 위로해본다...
profile
잡코딩

1개의 댓글

comment-user-thumbnail
2022년 8월 30일

같은 고민을 하고있었는데 , 덕분에 잘 해결했습니다! 너무 감사합니다 !!

답글 달기