Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify a BeanNamingStrategy with Spring Boot?

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?

like image 407
Adam Burley Avatar asked Oct 12 '15 11:10

Adam Burley


People also ask

How do you specify the 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 specify a bean name you want injected?

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.


2 Answers

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);
    }
}
like image 54
BeshEater Avatar answered Nov 11 '22 11:11

BeshEater


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.

like image 9
Sean Patrick Floyd Avatar answered Nov 11 '22 10:11

Sean Patrick Floyd