簡體   English   中英

如何在Spring MVC中將屬性注入攔截器

[英]How to inject property to interceptor in 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/**");
    }

你能說一下我在做什么錯嗎?

謝謝

您正在使用new關鍵字創建對象。 而是嘗試在您的Spring配置@Bean WebAuthenticationInterceptorMobileAuthenticationInterceptor定義為@Bean

注入是通過Spring注釋進行的,從3.x版本開始,它還可以與Java注釋(@Inject)一起使用。

采用

@Autowired
private IAuthenticationService authenticationService;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM