Reputation: 4372
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?
Upvotes: 2
Views: 2173
Reputation: 131346
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)
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.
Upvotes: 1
Reputation: 22422
Would MyInterceptor have to be declared as a bean or can I just instantiate it on my own like this?
Already answered by David, just adding one more point:
If there is a singleton object, then it is ALWAYS better to leave it for the Spring container to maintain/manage it as a singleton scoped bean (default scope), rather than developers manually using new MyInterceptor()
and creating & ensuring single instance of the class.
This concept is applicable NOT only for MyInterceptor
, rather needs to be followed for all singleton scoped objects (like Services, DAOs, Filters, etc..).
Further Explanation:
What I mean is that when you have taken the control (of creation) of few beans (like interceptors), then at some time of time, your application will end up in a messy state i.e., some of the singleton beans are maintained by Spring Container and some of the beans are created by developers using new
operator (which can't be easily differentiated causing lots of confusion). So the best practice is that to leave the creation of all singleton-scoped beans (atleast) to the Spring container itself.
Upvotes: 1