java – 是否可以在Spring Framework中使用注释设置bean名称?
作者:互联网
我有这样的豆:
@Bean
public String myBean(){
return "My bean";
}
我想要自动装配它:
@Autowired
@Qualifier("myBean")
public void setMyBean(String myBean){
this.myBean=myBean;
}
我需要这样的东西:
@Bean(name="myCustomBean")
是否可以使用开箱即用的bean自定义名称?如果不可能开箱即可,那么如何创建这样的bean呢?
解决方法:
您可以使用任何一个@Component注释来设置名称.
这是official doc.
@Service("myMovieLister")
public class SimpleMovieLister {
// ...
}
这将创建一个bean,即myMovieLister,而不是simpleMovieLister.
对于JavaConfig,这适用于使用@Bean的示例.
2.2.6. Customizing bean naming
By default, JavaConfig uses a @Bean method’s name as the name of the
resulting bean. This functionality can be overridden, however, using
the BeanNamingStrategy extension point.
public class Main {
public static void main(String[] args) {
JavaConfigApplicationContext ctx = new JavaConfigApplicationContext();
ctx.setBeanNamingStrategy(new CustomBeanNamingStrategy());
ctx.addConfigClass(MyConfig.class);
ctx.refresh();
ctx.getBean("customBeanName");
}
}
============================
更新:
你问的问题已经在4.3.3春季开始了
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();
}
}
标签:java,spring,spring-mvc,spring-annotations,spring-bean 来源: https://codeday.me/bug/20190930/1836040.html