I want to specify a custom BeanNamingStrategy
while configuring my application with Spring Boot. By default, Spring Boot uses the MethodNameStrategy
which is a BeanNamingStrategy
.
The reason I want to do this is because I have abstract parent classes which my consumers will create configuration subclasses of. The methods in the parent classes have the same names as each other and so are not getting registered for different implementations of the child classes. My custom BeanNamingStrategy
will attach the simple name of the configuration class to certain bean names.
Normally in a Spring application you can pass a custom BeanNamingStrategy
using the setBeanNamingStrategy
method of the ApplicationContext
. However if Spring Boot is creating the ApplicationContext
, how can I do this?
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.
Using the @Qualifier annotation, I specify the name of the bean I want Spring to inject from the context, and I don't rely anymore on the identifier of the constructor's parameter.
You can also use @ComponentScan(nameGenerator = ...)
annotation on your main Spring Boot application class:
@SpringBootApplication
@ComponentScan(nameGenerator = FullyQualifiedAnnotationBeanNameGenerator.class)
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
The SpringApplicationBuilder has a method beanNameGenerator()
that lets you pass in a custom generator.
See 22.3 Fluent builder API in the Spring Boot reference for how to work with the fluent API.
Unfortunately this doesn't help you, as this only applies to @Component
-style class annotations and not to @Bean
methods, for which the names are hard coded using this method.
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