zero01alpha zero01alpha - 17 days ago 5
Java Question

Do Interceptors have to be beans?

Inside of my class that extends

WebMvcConfigurerAdapter
I want to add Interceptors like this

@Override
public void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);
registry.addInterceptor(new MyInterceptor());
}


Would
MyInterceptor
have to be declared as a bean, or can I just instantiate it on my own like this?

Answer

According to official documentation, your interceptors should be Spring beans if you declare them in the xml configuration.

Your called method :

InterceptorRegistration addInterceptor(HandlerInterceptor interceptor)

From https://docs.spring.io/spring/docs/4.0.3.RELEASE/javadoc-api/org/springframework/web/servlet/HandlerInterceptor.html :

org.springframework.web.servlet

Interface HandlerInterceptor

The interceptors themselves are defined as beans in the application context, referenced by the mapping bean definition via its "interceptors" property (in XML: a of ).

Update

What javaguy refers is letting Spring make the instantiation of the bean. It underlies that your interceptor follows the stateless principle.
To enable that, your interceptor should not have state (internal properties which change during the interceptor execution).
As a general rule, when it is possible, processing classes should try to not keep state.

Here how you could create your singleton interceptor with Spring :

@Configuration
public class YourSpringConf{

  @Bean
    public HandlerInterceptor myInterceptor() {
       return new MyInterceptor();
    }
}

In this way, you will have a Bean named myInterceptor managed by Spring and you can inject it in the addInterceptors() method.

Comments