是否可以在 Spring Framework 中使用注解设置 bean 名称?
Is it possible to set a bean name using annotations in Spring Framework?
我有一个这样的豆子:
@Bean
public String myBean(){
return "My bean";
}
我想自动装配它:
@Autowired
@Qualifier("myBean")
public void setMyBean(String myBean){
this.myBean=myBean;
}
我需要这样的东西:
@Bean(name="myCustomBean")
是否可以开箱即用地为 bean 使用自定义名称?如果开箱即用是不可能的,那么如何创建这样的 bean?
您要问的是 Spring reference
By default, configuration classes use a @Bean method’s name as the
name of the resulting bean. This functionality can be overridden,
however, with the name attribute.
@Configuration
public class AppConfig {
@Bean(name = "myFoo")
public Foo foo() {
return new Foo();
}
}
我有一个这样的豆子:
@Bean
public String myBean(){
return "My bean";
}
我想自动装配它:
@Autowired
@Qualifier("myBean")
public void setMyBean(String myBean){
this.myBean=myBean;
}
我需要这样的东西:
@Bean(name="myCustomBean")
是否可以开箱即用地为 bean 使用自定义名称?如果开箱即用是不可能的,那么如何创建这样的 bean?
您要问的是 Spring reference
By default, configuration classes use a @Bean method’s name as the name of the resulting bean. This functionality can be overridden, however, with the name attribute.
@Configuration
public class AppConfig {
@Bean(name = "myFoo")
public Foo foo() {
return new Foo();
}
}