Interceptor无法用Autowired自动注入Bean

参考文章:
http://blog.csdn.net/mjlfto/article/details/65635135

本文解决spring boot LoginInterceptor(登录拦截器)无法注入bean的问题.

public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private HS hs;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("hs object : " + hs);
        try {
            HttpSession session = request.getSession();
            System.out.println("session : " + session.getAttribute("scenicUser"));
            if (session.getAttribute("scenicUser") == null) {
                response.sendRedirect("/seengene/login");
                return false;
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

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

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

MyWebAppConfigurer代码:

@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        super.addInterceptors(registry);

        LoginInterceptor loginInterceptor1 = new LoginInterceptor();
        registry.addInterceptor(loginInterceptor1).addPathPatterns("/seengene/**")
                .excludePathPatterns("/seengene/login")
                .excludePathPatterns("/seengene/logindo");
    }
}

这个时候运行代码会出现:
hs object : null

解决办法:
将MyWebAppConfigurer代码该为如下:

@EnableWebMvc
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {

    @Bean
    LoginInterceptor localInterceptor() {
        return new LoginInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(localInterceptor()).addPathPatterns("/seengene/**")
                .excludePathPatterns("/seengene/login")
                .excludePathPatterns("/seengene/logindo");
    }
}

这样以后就可以正常注入bean。

本文借鉴:http://stackoverflow.com/questions/23349180/java-config-for-spring-interceptor-where-interceptor-is-using-autowired-spring-b

本站公众号
   欢迎关注本站公众号,获取更多程序园信息
开发小院