zero01alpha zero01alpha - 1 year ago 96
Java Question

Do Interceptors have to be beans?

Inside of my class that extends

I want to add Interceptors like this

public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor());

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

Answer Source

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 :


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 ).


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 :

public class YourSpringConf{

    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download