I have a bean B
which I have to create myself (using new B()
) and which has @Autowire
and @PostConstruct
annotations.
How do I make Spring process these annotations from my bean A
?
Related question:
In Spring, you can use @Autowired annotation to auto-wire bean on the setter method, constructor , or a field . Moreover, it can autowire the property in a particular bean. We must first enable the annotation using below configuration in the configuration file. We have enabled annotation injection.
Using the @Qualifier annotation you can specify which bean you want to autowire. Hope this helps. In my case there's only one bean of MyService . beanA and beanB names refer to BaseBean implementations.
@Bean methods may also be declared within classes that are not annotated with @Configuration. For example, bean methods may be declared in a @Component class or even in a plain old class. In such cases, a @Bean method will get processed in a so-called 'lite' mode.
In Spring Boot, we can use Spring Framework to define our beans and their dependency injection. The @ComponentScan annotation is used to find beans and the corresponding injected with @Autowired annotation. If you followed the Spring Boot typical layout, no need to specify any arguments for @ComponentScan annotation.
Aaron, I believe that your code is correct but I used the following:
B bean = new B(); AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory(); factory.autowireBean( bean ); factory.initializeBean( bean, "bean" );
The first method will process @Autowire
fields and methods (but not classic properties). The second method will invoke post processing (@PostConstruct
and any defined BeanPostProcessor
s).
Application context can be obtained in a bean if it implements ApplicationContextAware
interface.
Another option is to let the spring container create automatically a new bean (instead of creating a new instance yourself with the new keyword). Inside a class that needs to instantiate a new been programmatically, inject an instance of AutowireCapableBeanFactory :
@Autowired private AutowireCapableBeanFactory beanFactory;
Then:
B yourBean = beanFactory.createBean(B.class);
The container will inject instances annotated with @Autowired annotations as usual.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With