spring提供两种beanName生成策略,基于注解的sprongboot默认使用的是AnnotationBeanNameGenerator,它生成beanName的策略就是,取当前类名(不是全限定类名)作为beanName。由此,如果出现不同包结构下同样的类名称,肯定会出现冲突。
解决方法如下:
一、自己写一个类实现 org.springframework.beans.factory.support.BeanNameGeneraot接口
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
public class UniqueNameGenerator extends AnnotationBeanNameGenerator {
@Override
public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
/**
* 全限定类名
*/
String beanName = definition.getBeanClassName();
return beanName;
}
}
二、在启动类上加注解@ComponentScan(nameGenerator = UniqueNameGenerator.class)使刚才我们自定义的BeanName生成策略生效。
@SpringBootApplication
@ComponentScan(nameGenerator = UniqueNameGenerator.class)
public class CommunityApplication {
public static void main(String[] args) {
SpringApplication.run(CommunityApplication.class, args);
}
}