简体   繁体   English

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

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

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?是否可以开箱即用地为 bean 使用自定义名称? If it isn't possible out of the box then how to create such a bean?如果无法开箱即用,那么如何创建这样的 bean?

What you are asking is already available in Spring reference您要问的内容在 Spring 参考中可用

By default, configuration classes use a @Bean method's name as the name of the resulting bean.默认情况下,配置类使用@Bean 方法的名称作为结果 bean 的名称。 This functionality can be overridden, however, with the name attribute.但是,可以使用 name 属性覆盖此功能。

@Configuration
public class AppConfig {

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring 中使用 @Bean 和 @Qualifier 注释的 Bean 名称解析 - Bean name resolution in Spring using @Bean and @Qualifier annotations 如果在Spring中将属性设置为不同的Bean列表,则可以使用注释创建Bean吗? - Is it possible in Spring to create beans using annotations if they have properties set to different bean lists? 使用Java Spring中的注释将数据库列名称映射到Bean属性 - Mapping a DB column name to a Bean property using annotations in Java Spring 如何动态创建Spring bean和在新创建的bean上设置注释 - How to Dynamically create Spring bean and Set Annotations on the newly created bean 使用注释时的Spring Mvc DataSource Bean - Spring Mvc DataSource Bean when using annotations 如何使用注释设置MessageDriven bean的主体? - How to set the principal of a MessageDriven bean using annotations? 如何使用注解Bean和ComponentScan正确创建Bean Spring? - How to proper create bean Spring using annotations Bean and ComponentScan? 使用ehcache Spring注释为cacheManager自动装配Spring bean null - Autowired spring bean null for cacheManager using ehcache spring annotations Spring Framework 错误创建具有名称的 bean 并且没有符合条件的 bean 类型 - Spring Framework Error creating bean with name and No qualifying bean of type 使用HttpRequest初始化Spring Session Bean(使用批注) - Initializing a Spring Session Bean using an HttpRequest (using annotations)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM