Issue
I can declare a bean in Spring using @Bean annotation. Let's say I declare two beans of String type in my Application Context.
@Bean
public String country(){ return "India";}
@Bean
public String continent(){ return "Asia";}
In this case what will happen when the Spring Container will boot strap? Would there be any error?
Solution
You can have beans of the same type in the same context. Both beans will have a different name (country
and continent
) derived from the method names:
@Configuration
public class Config {
@Bean
public String country() {
return "Germany";
}
@Bean
public String continent() {
return "Europe";
}
}
Therefore you can wire the beans by name:
@Autowired
String country;
@Autowired
String continent;
You can also define a name explicitly if needed:
@Bean(name = "myContinent")
public String continent() {
return "Europe";
}
And then wire using the @Qualifier
:
@Qualifier("myContinent")
@Autowired
String continent;
Answered By - Gregor Zurowski