2013-06-20 71 views
2

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

的代码如下所示:

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/**"); 
    } 

你能请注明什么我做错了什么?

谢谢

+5

您正在使用'new'关键字创建对象。相反,在你的Spring配置中尝试将'WebAuthenticationInterceptor'和'MobileAuthenticationInterceptor'定义为'@ Bean'。 – dimchez

+0

@dimchez将此添加为答案。 –

+0

@TomG好吧,发表我的评论作为回答 – dimchez

回答

1

注射液是由Spring注解制成,因为3.x版它的工作原理也与Java注解(@注入)。

使用

@Autowired 
private IAuthenticationService authenticationService; 
+0

这不会回答这个问题。考虑审查你的答案。 –

+0

我使用@Autowired注释来注入依赖关系。可能它不是我现在在3年后看到的唯一问题,但仍然使用该注释似乎是一种正确的方法。 –

3

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

相关问题