简体   繁体   中英

How can I create two beans of same class in a Spring Context?

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?

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;

Two spring beans can be created in same context. But they need to be created in separate @Configuration files and separate access.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM