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

时光怂恿深爱的人放手 提交于 2019-11-30 04:43:42

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

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

This will create a bean namely myMovieLister instead of simpleMovieLister.

For JavaConfig, This is applicable for your example which is using @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");
    }
} 

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

Update:

What you are asking is already available in 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.

@Configuration
public class AppConfig {

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

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!