简体   繁体   中英

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?

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 .

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM