Automatically assign spring's bean name to prevent name conflicts?

后端 未结 2 1729
情话喂你
情话喂你 2021-02-07 13:15

In a spring app , if two programmers develop two packages , annotating @Repository to the same class name , Spring will throw \"IllegalStateException\" :

相关标签:
2条回答
  • 2021-02-07 13:40

    Somewhere in your config, you've enabled classpath scanning, probably using

    <context:component-scan>
    

    You can specify a property called name-generator, which takes a bean that implements the BeanNameGenerator interface. Create your own implementation of that interface and provide a reference to it.

    0 讨论(0)
  • 2021-02-07 13:42

    This is because it is using AnnotationBeanNameGenerator which simply put non-qualified name(class name) as the bean name, then caused conflict.

    Two steps to resolve this:

    1、You can implement your own bean name generation strategy which use fully-qualified name (package + class name) like below

    public class UniqueNameGenerator extends AnnotationBeanNameGenerator {
        @Override
        public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
            //use fully-qualified name as beanName
            String beanName = definition.getBeanClassName();
            return beanName;
        }
    }
    

    2、Add @ComponentScan(nameGenerator = UniqueNameGenerator.class) to configuration or Boot class if you are using SpringBoot

    @Configuration
    @ComponentScan(nameGenerator = UniqueNameGenerator.class)
    public class Config {
    }
    
    0 讨论(0)
提交回复
热议问题