是否可以在Spring Framework中使用注释设置bean名称? [英] Is it possible to set a bean name using annotations in Spring Framework?

查看:113
本文介绍了是否可以在Spring Framework中使用注释设置bean名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的bean:

@Bean
public String myBean(){
    return "My bean";
}

我想自动装箱:

@Autowired
@Qualifier("myBean")
public void setMyBean(String myBean){
    this.myBean=myBean;
}

我需要这样的东西:

@Bean(name="myCustomBean")

是否可以使用开箱即用的bean自定义名称?如果开箱即可,那么如何创建这样的bean?

Is it possible to use custom names names for beans out of the box? If it isn't possible out of the box then how to create such a bean?

推荐答案

你可以设置使用任何 @Component 注释中的任何一个来命名。
这是官方文件。

You can set the name by using any one of the @Component annotations. Here is the official doc.

@Service("myMovieLister")
public class SimpleMovieLister {
    // ...
}

这将创建一个bean,即 myMovieLister 而不是simpleMovieLister。

This will create a bean namely myMovieLister instead of simpleMovieLister.

对于JavaConfig,这适用于您的示例是使用@Bean

For JavaConfig, This is applicable for your example which is using @Bean.


2.2.6。自定义bean命名

2.2.6. Customizing bean naming

默认情况下,JavaConfig使用 @Bean 方法的名称作为
结果bean的名称。但是,使用
BeanNamingStrategy 扩展点可以覆盖此功能。

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");
    }
} 

=========== =================

============================

更新:

你问的是Spring中的已经可用 4.3.3

What you are asking is already available in Spring 4.3.3


默认情况下,配置类使用@Bean方法的名称作为结果bean的
名称。可以使用name属性覆盖此功能,

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();
    }

}

这篇关于是否可以在Spring Framework中使用注释设置bean名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆