Is it possible to set a bean name using annotations in Spring Framework?
100,129
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();
}
}
Author by
Oleksandr
Updated on July 09, 2022Comments
-
Oleksandr almost 2 years
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?
-
Oleksandr over 7 yearsThank you for help. I think I have not clear question. I wanted to use custom names. Also, you can not use @Component annotations on methods.
-
Sundararaj Govindasamy over 4 years@Noel Yap, I retained that 'extra information' to remember how spring evolved on this. That's why I strike-out that text. Could you please re-add? Thanks.
-
Noel Yap over 4 yearsIMO such history doesn't belong in this answer. For example, I almost missed the actual answer since I almost stopped reading after the first few sentences. Foremost to consider is the purpose of SO and the primary problem those using it are trying to solve.
-
Noel Yap over 4 yearsAlternatively, the original, legacy answer could have been kept and a new, more up-to-date one created.