Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BeanPostProcessor not called for @Bean methods with Spring Java Config

I am trying to add a BeanPostProcessor in my Spring Java Config. It seems to be working but only for beans that are created through component scanning (@Configuration, @RestController, ..)

Beans that I create in my Java config are not.

E.g.

@Configuration
public class MyConfiguration
{
  @Bean
  public MyBean myBean()
  {
    return new MyBean();
  }


  @Bean
  public static MyBPP myBeanPostProcessor()
  {
    return new MyBPP();
  }
}

Notice I did declare the method of the BeanPostProcessor as static (See http://forum.spring.io/forum/spring-projects/container/123899-beanpostprocessor-with-bean-annotation-not-working).

So an instance of MyBean gets created but the BeanPostProcessor never processes it.

like image 586
Wim Deblauwe Avatar asked May 04 '26 01:05

Wim Deblauwe


1 Answers

try my test, it worked for me

class MyBPP implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        System.out.println(bean);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        return bean;
    }
}

@Configuration
public class MyConfiguration {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }

    @Bean
    public MyBPP myBeanPostProcessor() {
        return new MyBPP();
    }

    public static void main(String[] args) {
        new AnnotationConfigApplicationContext(MyConfiguration.class);
    }
}
like image 137
Evgeniy Dorofeev Avatar answered May 05 '26 14:05

Evgeniy Dorofeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!