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?
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();
}
}
来源:https://stackoverflow.com/questions/39898028/is-it-possible-to-set-a-bean-name-using-annotations-in-spring-framework