'How do I register a HandlerInterceptor with constructor dependencies in Spring Boot

My use case is running custom code before a controller method by annotating methods.

HandlerInterceptor seems the way to go but it seems impossible to inject dependencies into it because it needs to be registered before the context is being created.

All examples I've found so far use empty constructors (see spring boot adding http request interceptors) or autowire properties in the configuration which fails because I declare dependent beans in the same configuration (Requested bean is currently in creation: Is there an unresolvable circular reference?).

Is there a better way that does not involve AOP?



Solution 1:[1]

Assume that your interceptor has constructor dependencies like that:

public class CustomInterceptor extends HandlerInterceptor {

    private final DependentBean bean;

    public CustomInterceptor(DependentBean bean) {
        this.bean = bean;
    }
}

Then you can register your handler like that:

@Configuration
public WebConfig extends WebMvcConfigurerAdapater {

    @Bean
    public DependentBean dependentBean() {
       return new DependentBean();
    }


    @Bean
    public CustomInterceptor customInterceptor() {
         return new CustomInterceptor(dependentBean());
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
         registry.addInterceptor(customInterceptor());
    }
}

@Configuration will ensure each Bean method call return the same bean instance

Solution 2:[2]

Building on the answer above from M?nh, if using component scan for dependency injection of the dependency, then that can be Autowired in the WebConfig

@Configuration
public WebConfig extends WebMvcConfigurerAdapater {

    @Autowired
    DependentBean dependentBean;

    @Bean
    public CustomInterceptor customInterceptor() {
         return new CustomInterceptor(dependentBean);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
         registry.addInterceptor(customInterceptor());
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 M?nh Quy?t Nguy?n
Solution 2