With @Configuration
classes
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);
}
The BeanPostProcessor
doesn't "exist" yet so it can't process the other bean being created (that's required by the @Autowired
to finish this bean). The javadoc states
ApplicationContexts can autodetect BeanPostProcessor beans in their
bean definitions and apply them to any beans subsequently created.
Bold mine.
With 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);