Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? If it isn't possible out of the box then how to create such a bean?

like image 324
Oleksandr Avatar asked Oct 06 '16 13:10

Oleksandr


People also ask

How do you give an annotation a bean name?

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.

How do you get the bean name in Spring?

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.

How do you annotate a bean in the Spring?

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.

What is the use of @bean name?

@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 .


1 Answers

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();     }  } 
like image 137
Sundararaj Govindasamy Avatar answered Sep 21 '22 17:09

Sundararaj Govindasamy