By using Java Config, how can I wire a bean in the same class when it is defined?
For example:
@Bean
public Foo foo() {
return new Foo();
}
@Autowired
private Foo foo;
@Bean
public Bar bar() {
return new Bar(foo);
}
Note: this code returns an error.
No. It is used to explicitly declare a single bean, rather than letting Spring do it automatically. If any class is annotated with @Component it will be automatically detect by using classpath scan. We should use @bean, if you want specific implementation based on dynamic condition.
This is the simplest and easiest way to create multiple beans of the same class using annotations. In this approach, we'll use a Java-based configuration class to configure multiple beans of the same class.
The default autowiring is by type, not by name, so when there is more than one bean of the same type, you have to use the @Qualifier annotation.
It will throw an error at runtime, as you can not define two Sspring beans of the same class with Singleton Scope in XML.
@Bean
public Foo foo() {
return new Foo();
}
@Bean
public Bar bar() {
return new Bar(foo());
}
Alternatively the Bar
bean could also be configured as so:
@Bean
public Bar bar(Foo foo) {
return new Bar(foo);
}
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