码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot 拦截器中无法使用 @Autowired 注入 Service

时间:2018-05-16 15:07:51      阅读:1267      评论:0      收藏:0      [点我收藏+]

标签:adapter   red   extends   use   mvcc   model   row   exception   pattern   

进行如下修改即可。

首先是 WebMvcConfiguration

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {

    @Bean
    public AuthenticationInterceptor authenticationInterceptor() {
        return new AuthenticationInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authenticationInterceptor()).addPathPatterns("/**");
    }

}

然后需要使 springboot 扫描到当前 Interceptor,也就是在类上加上 @Component 注释。

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        User user = userService.getById(id);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
    }

}

SpringBoot 拦截器中无法使用 @Autowired 注入 Service

标签:adapter   red   extends   use   mvcc   model   row   exception   pattern   

原文地址:https://www.cnblogs.com/StarUDream/p/9045500.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!