1

我有一个实现弹簧 BeanPostProcessor 的 A 类

public class A implements BeanPostProcessor {


   private B b;

   public A() {
      b = new B();
      b.set(...);          
   }


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

   // Intercept all bean initialisations and return a proxy'd bean equipped with code
   // measurement capabilities
   public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    return b.enhance(bean);
   }


}

我想配置我的类 b,它位于派生的 BeanPostProcessor 类 A 中。如何使用 spring 配置(依赖注入)这个类,这可能在 BeanPostProcessor 中......?

4

2 回答 2

2

@Configuration

public static class Child {}

public static class Processor implements BeanPostProcessor {        
    @Autowired
    public Child child;             
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return null; // Spring would complain if this was executed
    }
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return null; // Spring would complain if this was executed
    }       
}

@Configuration
public static class Config {
    @Bean
    public static Processor processor() {
        return new Processor();
    }
    @Bean
    public Child child() {
        return new Child();
    }
}

public static void main(String[] args) throws IOException, ParseException, JAXBException, URISyntaxException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {     
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
    Processor processor = context.getBean(Processor.class);
    System.out.println(processor.child);
}

BeanPostProcessor尚未“存在”,因此它无法处理正在创建的其他 bean(这是完成此 bean 所必需的)@Autowiredjavadoc状态_

ApplicationContexts 可以在它们的 bean 定义中自动检测 BeanPostProcessor bean 并将它们应用于随后创建的任何 bean

大胆的我。

使用 XML

<context:component-scan base-package="test"></context:component-scan>
<bean id="processor" class="test.Main.Processor"></bean>
<bean id="child" class="test.Main.Child"></bean>

ClassPathXmlApplicationContext xmlContext = new ClassPathXmlApplicationContext("context.xml");
processor = xmlContext.getBean(Processor.class);
System.out.println(processor.child);
于 2013-08-29T13:48:38.507 回答
1

您当然可以在 BeanPostProcessor 类中应用依赖注入。

以下是Spring 文档的摘录

实现 BeanPostProcessor 接口的类是特殊的,因此容器对它们的处理方式不同。所有 BeanPostProcessor 及其直接引用的 bean 将在启动时实例化,作为 ApplicationContext 特殊启动阶段的一部分,然后所有这些 BeanPostProcessor 将以排序方式注册 - 并应用于所有其他 bean。

于 2013-08-29T13:49:49.513 回答