java – 是否可以在Spring Framework中使用注释设置bean名称?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 是否可以在Spring Framework中使用注释设置bean名称?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1337字,纯文字阅读大概需要2分钟。
内容图文
![java – 是否可以在Spring Framework中使用注释设置bean名称?](/upload/InfoBanner/zyjiaocheng/706/954faa3e066e40388141fc2877155b6b.jpg)
我有这样的豆:
@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 Framework中使用注释设置bean名称?全部内容,希望文章能够帮你解决java – 是否可以在Spring Framework中使用注释设置bean名称?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。