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();
}
}
C - This annotation simply indicates that the affected bean property must be populated at configuration time, through an explicit property value in a bean definition or through autowiring.
A lesser known nugget of information is that you can also use the @Value annotation to inject values from a property file into a bean's attributes.
We can also use the @Qualifier annotation to name the bean.
Here is a first solution, where you have both bean definitions in one @Configuration
class.
@Configuration
class GlobalConfiguration {
@Bean
public Example createExample(){
final Example example = new Example();
example.setSomeProp(createAnotherBean());
return example;
}
@Bean
public AnotherBean createAnotherBean(){
return new AnotherBean();
}
}
Second possibility is to use autowiring like below:
@Configuration
class GlobalConfiguration {
@Bean
@Autowired
public Example createExample(AnotherBean anotherBean){
final Example example = new Example();
example.setSomeProp(anotherBean);
return example;
}
@Bean
public AnotherBean createAnotherBean(){
return new AnotherBean();
}
}
Third possibility is to split those declarations among two different @Configuration
classes and use autowiring.
@Configuration
class FirstConfiguration {
@Bean
public AnotherBean createAnotherBean(){
return new AnotherBean();
}
}
@Configuration
class SecondConfiguration {
@Autowired
private AnotherBean anotherBean;
@Bean
public Example createExample(){
final Example example = new Example();
example.setSomeProp(anotherBean);
return example;
}
}
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