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?
Custom Naming of Beans Similar to @Component(“myBean”), we can specify the name using other annotations such as @Service(“myService”), @Controller(“myController”), and @Bean(“myCustomBean”), and then Spring will register that bean with the given name.
So that Spring can inject the beanName into the bean. If you add a public String getBeanName(); in your DashboardDAO interface, DashboardDaoConsumer will be able to obtain it. In this particular case, Spring will inject the name you specified in the annotation.
Spring @Bean Annotation is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. In this case, bean methods may reference other @Bean methods in the same class by calling them directly.
@Bean is a method-level annotation and a direct analog of the XML <bean/> element. The annotation supports most of the attributes offered by <bean/> , such as: init-method , destroy-method , autowiring , lazy-init , dependency-check , depends-on and scope .
What you are asking is already available in Spring reference
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(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With