如何在 Spring 中为包(包括子包)中的每个 bean id 添加常量字符串前缀?

Chr*_*ian 4 java spring

有没有办法为@Component某个包和子包中注释的每个 bean 加上给定的字符串前缀?

假设我们有这个 bean,例如:

package com.example.foo;

@Component
class MyBean {}
Run Code Online (Sandbox Code Playgroud)

我希望所有 bean 都foo以 为前缀foo,以便自动(通过组件扫描)生成的 bean id 为fooMyBean(首选,大写“M”)或foo-myBean(而不是默认值myBean)。(前缀是在某处定义的字符串,不是从包名称自动派生的。)

或者,我可以通过使用自定义注释(例如@FooComponent,例如)来实现此目的吗?(如何? ;-) )

Cri*_*eco 5

Spring 使用BeanNameGenerator策略来生成 bean 名称。特别是,AnnotationBeanNameGenerator@Component是使用首字母小写策略生成类名称的。

您可以实现自己的BeanNameGenerator策略并通过检查传递的BeanDefinition.

如果您使用 Spring Boot,则可以直接在SpringApplicationBuilder中完成此操作。

@SpringBootApplication
public class DemoApplication {

    public static class CustomGenerator extends AnnotationBeanNameGenerator {

        @Override
        public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
            /**
              * access bean annotations or package ...
              */
            return super.generateBeanName(definition, registry);
        }
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(DemoApplication.class)
                .beanNameGenerator(new CustomGenerator())
                .run(args);
    }
}
Run Code Online (Sandbox Code Playgroud)