有@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 所必需的)@Autowired
。javadoc状态_
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);