Java 是否可以在 Spring Framework 中使用注释设置 bean 名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39898028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:32:44  来源:igfitidea点击:

Is it possible to set a bean name using annotations in Spring Framework?

javaspringspring-mvcspring-annotationsspring-bean

提问by Oleksandr

I have a bean like this:

我有一个这样的豆子:

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

I want to autowire it:

我想自动装配它:

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

I need something like:

我需要类似的东西:

@Bean(name="myCustomBean")

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?

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

采纳答案by Sundararaj Govindasamy

What you are asking is already availablein Spring 4.3.3

您所问的在 Spring 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.

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

@Configuration
public class AppConfig {

    @Bean(name = "myFoo")
    public Foo foo() {
        return new Foo();
    }

}