如何在Spring中后处理其他BeanPostProcessor-s?

时间:2015-11-02 11:48:40

标签: java spring post-processing

我在想,BeanPostProcessor应该在上下文中接收每个bean的调用。不幸的是,我发现如果其他bean也是后处理器也不行。

代码如下:

public class MutualBeanPostProcessorTest {

   @Configuration
   public static class Config {

      @Bean
      public Bean0 bean0() {
         return new Bean0();
      }

      @Bean
      public Bean1 bean1() {
         return new Bean1();
      }

      @Bean
      public Bean2 bean2() {
         return new Bean2();
      }

      @Bean
      public Bean3 bean3() {
         return new Bean3();
      }
   }

   public static class Bean0  {
      {
         System.out.println("Constructor of " + this.getClass().getSimpleName());
      }
   }

   public static class Bean1 implements BeanPostProcessor {
      {
         System.out.println("Constructor of " + this.getClass().getSimpleName());
      }

      public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
         return bean;
      }

      public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
         System.out.println("Postprocessor Bean1 called for " + beanName);
         return bean;
      }
   }

   public static class Bean2 implements BeanPostProcessor {
      {
         System.out.println("Constructor of " + this.getClass().getSimpleName());
      }

      public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
         return bean;
      }

      public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
         System.out.println("Postprocessor Bean2 called for " + beanName);
         return bean;
      }
   }

   public static class Bean3 {
      {
         System.out.println("Constructor of " + this.getClass().getSimpleName());
      }
   }

   public static void main(String[] args) {
      new AnnotationConfigApplicationContext(Config.class);
   }

}

输出如下:

Constructor of Bean2
Constructor of Bean1
Postprocessor Bean2 called for org.springframework.context.event.internalEventListenerProcessor
Postprocessor Bean1 called for org.springframework.context.event.internalEventListenerProcessor
Postprocessor Bean2 called for org.springframework.context.event.internalEventListenerFactory
Postprocessor Bean1 called for org.springframework.context.event.internalEventListenerFactory
Constructor of Bean3
Postprocessor Bean2 called for bean3
Postprocessor Bean1 called for bean3
Constructor of Bean0
Postprocessor Bean2 called for bean0
Postprocessor Bean1 called for bean0

即。没有后期任何人处理另一个。

如何解决?

0 个答案:

没有答案