如何在Spring MVC中为拦截器注入属性

时间:2013-06-20 10:59:37

标签: java spring spring-mvc

我将spring mvc应用程序配置从xml更改为代码。 自更改以来,拦截器中的所有注入属性都为null(authenticationService)。

代码如下所示:

public class WebAuthenticationInterceptor extends HandlerInterceptorAdapter {


    @Resource(type=WebAuthenticationService.class)
    private IAuthenticationService authenticationService;

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {


        if(authenticationService.authenticate(request).authenticated == false)
        {
            if(isAjax(request))
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            else
                response.sendRedirect(String.format("%s/#/account/logout", request.getContextPath()));

            return false;
        }
        return true;

    }

    public static boolean isAjax(HttpServletRequest request) {
        return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
    }
}

和拦截器配置:

@Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new WebAuthenticationInterceptor()).addPathPatterns("/home/**");
        registry.addInterceptor(new MobileAuthenticationInterceptor()).addPathPatterns("/api/**");
    }

请你说出我做错了什么?

谢谢

2 个答案:

答案 0 :(得分:3)

您正在使用new关键字创建对象。而是尝试在Spring配置中将WebAuthenticationInterceptorMobileAuthenticationInterceptor定义为@Bean

答案 1 :(得分:1)

注入由Spring注释完成,从3.x版本开始,它也适用于java注释(@Inject)。

使用

@Autowired
private IAuthenticationService authenticationService;