user1882324
user1882324

Reputation: 31

How to inject property to interceptor in Spring MVC

I changed my spring mvc application configuration from xml to code. since the change, all the injected properties in my interceptors are null (authenticationService).

the code looks like this:

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

and the interceptor config:

@Override
    public void addInterceptors(InterceptorRegistry registry) {

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

Could you please state what am i doing wrong ?

Thank you

Upvotes: 3

Views: 4910

Answers (2)

dimchez
dimchez

Reputation: 2004

You are creating object using new keyword. Instead try defining WebAuthenticationInterceptor and MobileAuthenticationInterceptor as @Bean in your Spring config

Upvotes: 4

Martin Strejc
Martin Strejc

Reputation: 4347

Injection is made by Spring annotation and since 3.x version it works also with java annotation (@Inject).

use

@Autowired
private IAuthenticationService authenticationService;

Upvotes: 0

Related Questions