'How to refer to another bean as a property in annotation-based configuration file
In XML context based bean configuration file, if I want to refer a bean as property, I would use:
<bean class="com.example.Example" id="someId">
<property name="someProp" refer="anotherBean"/>
</bean>
<bean class="com.example.AnotherBean" id="anotherBean">
</bean>
So the Example bean will use the anotherBean as its property
So in the concept of annotation-based configuration java file:
@Configuration
class GlobalConfiguration {
@Bean
public Example createExample(){
return;
//here how should I refer to the bean below?
}
@Bean
public AnotherBean createAnotherBean(){
return new AnotherBean();
}
}
Solution 1:[1]
Just do:
@Configuration
class GlobalConfiguration {
@Bean
public Example createExample(@Autowired AnotherBean anotherBean){
//use another bean
return new Example(anotherBean);
}
@Bean
public AnotherBean createAnotherBean(){
return new AnotherBean();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Apurva Singh |
