Init BeanPostProcessor at a later point

I’m developing an external component for applications which contains functionality to inject Jersey Client filters into lazy-loaded clients. Ive implemented a BeanPostProcessor that does this:

public class ClientFilterInjector implements BeanPostProcessor, Ordered {


    private ClientTraceInterceptor clientTraceInterceptor;

    public ClientFilterInjector(ClientTraceInterceptor clientTraceInterceptor) {
        this.clientTraceInterceptor = clientTraceInterceptor;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        if(bean instanceof JerseyWebTarget) {
            ((JerseyWebTarget) bean).register(clientTraceInterceptor);
        }
        return bean;
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}

However, Spring Boot apparently auto-scans for BeanPostProcessor implementations regardless of whether or not they’re annotated or have a bean creation method. Because of this, it screws up the order for which beans are created in the application. Is there a way to defer the instantiation of a BeanPostProcessor?

Answer

It looks like if you implement BeanProcessor in the form of an anonymous class it will not get auto-scanned in the Spring Boot application init and you can defer its instantiation whenever you want by adding it to the bean factory of the application context.

((ConfigurableApplicationContext) appContext).getBeanFactory().addBeanPostProcessor(new BeanPostProcessor() {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(bean instanceof WebTarget) {
            ((WebTarget) bean).register(instance);
        }
        return bean;
    }
});