How do I prefix each bean id in a package (inc. sub-packages) with a constant string in Spring?

前端 未结 1 1568
眼角桃花
眼角桃花 2020-12-11 11:13

Is there a way to prefix each bean annotated with @Component in a certain package and subpackages with a given string?

Say, we have this bean, for examp

相关标签:
1条回答
  • 2020-12-11 11:38

    Spring uses a BeanNameGenerator strategy to generate bean names. In particular, the AnnotationBeanNameGenerator is the one which generates names for @Component classes with the first-letter-lower-cased strategy.

    You could implement your own BeanNameGenerator and apply a custom strategy by inspecting the passed BeanDefinition.

    If you're using Spring Boot, this can be done right in the 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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题