Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I manually autowire a bean with Spring?

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, can I autowire new beans from inside an autowired bean?
like image 335
Aaron Digulla Avatar asked Aug 15 '12 07:08

Aaron Digulla


People also ask

How do you Autowire beans in Spring?

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.

How do I specify a bean to Autowire?

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.

Can we use @bean without @configuration?

@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.

How do you inject specific beans in a Spring boot?

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.


2 Answers

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 BeanPostProcessors).

Application context can be obtained in a bean if it implements ApplicationContextAware interface.

like image 73
AlexR Avatar answered Sep 22 '22 17:09

AlexR


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.

like image 42
Domenico Avatar answered Sep 25 '22 17:09

Domenico