2013-06-20 113 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

相關問題