Issue
Lets say that in an external config a bean is wired with name "externalBean".
Ex.
@Bean("externalBean")
public Foo foo() {
Foo foo = new Foo();
return foo;
}
If I do the following in my own config:
@Bean("myBean")
public Foo foo(@Qualifier("externalBean") Foo foo) {
return foo;
}
I can now autowire the bean in my code by using @Qualifier("myBean").
Is it correct to say that myBean is now an alias for the externalBean?
Is there now only one instance of the Foo bean?
Any remarks?
Solution
Suppose it is effectively an alias as there will only be one instance of Foo, although there will still be two beans. These will both just return the same reference to the Foo object.
Try for example
@SpringBootApplication
public class BeanApp{
public static void main(String[] args) {
SpringApplication.run(BeanApp.class, args);
}
static class Foo {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Bean("externalBean")
public Foo foo(){
return new Foo();
}
@Bean("myBean")
public Foo foo1(@Qualifier("externalBean") Foo foo){
return foo;
}
@Bean
public String ready(@Qualifier("externalBean") Foo foo, @Qualifier("myBean") Foo foo1){
foo.setName("This is a bean");
System.out.println(foo.getName());
System.out.println(foo1.getName());
return "Ready";
}
}
This will print "This is a bean" twice, even though getName is called from the two separate beans.
Answered By - 123
Answer Checked By - Pedro (JavaFixing Volunteer)