我將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/**");
}
你能請註明什麼我做錯了什麼?
謝謝
您正在使用'new'關鍵字創建對象。相反,在你的Spring配置中嘗試將'WebAuthenticationInterceptor'和'MobileAuthenticationInterceptor'定義爲'@ Bean'。 – dimchez
@dimchez將此添加爲答案。 –
@TomG好吧,發表我的評論作爲回答 – dimchez