简体   繁体   English

如何使用 Spring Boot 指定 BeanNamingStrategy?

[英]How do I specify a BeanNamingStrategy with Spring Boot?

I want to specify a custom BeanNamingStrategy while configuring my application with Spring Boot.我想在使用 Spring Boot 配置我的应用程序时指定一个自定义BeanNamingStrategy By default, Spring Boot uses the MethodNameStrategy which is a BeanNamingStrategy .默认情况下,Spring Boot 使用MethodNameStrategy ,它是一个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.我的自定义BeanNamingStrategy会将配置类的简单名称附加到某些 bean 名称。

Normally in a Spring application you can pass a custom BeanNamingStrategy using the setBeanNamingStrategy method of the ApplicationContext .通常在 Spring 应用程序中,您可以使用ApplicationContextsetBeanNamingStrategy方法传递自定义BeanNamingStrategy However if Spring Boot is creating the ApplicationContext , how can I do this?但是,如果 Spring Boot 正在创建ApplicationContext ,我该怎么做?

The SpringApplicationBuilder has a method beanNameGenerator() that lets you pass in a custom generator. SpringApplicationBuilder 有一个方法beanNameGenerator()可以让你传入一个自定义生成器。

See 22.3 Fluent builder API in the Spring Boot reference for how to work with the fluent API.有关如何使用 fluent API,请参阅 Spring Boot 参考中的22.3 Fluent builder 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 .不幸的是,这对您没有帮助,因为这仅适用于@Component样式的类注释,而不适用于使用此方法对其名称进行硬编码的@Bean 方法

You can also use @ComponentScan(nameGenerator = ...) annotation on your main Spring Boot application class:您还可以在主 Spring Boot 应用程序类上使用@ComponentScan(nameGenerator = ...)注释:

@SpringBootApplication
@ComponentScan(nameGenerator = FullyQualifiedAnnotationBeanNameGenerator.class)
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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