一.写一个类继承AnnotationBeanNameGenerator类
import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.annotation.AnnotationBeanNameGenerator; /** * 自定义个BeanName生成策略, 解决不同包下同名类问题 */ public class UniqueNameGenerator extends AnnotationBeanNameGenerator { @Override public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) { System.out.println("BeanDefinition: "+definition.getBeanClassName()); String result = ""; String urlStartStr = "com.example.demo"; if(definition.getBeanClassName().startsWith(urlStartStr)){ result = definition.getBeanClassName(); } else { String[] strArr = definition.getBeanClassName().split("\\."); result = strArr[strArr.length-1]; result = result.substring(0, 1).toLowerCase() + result.substring(1); } return result; } }
二.在springboot启动类中配置自定义bean名称生成器,使其生效
@SpringBootApplication
@ComponentScan(basePackages = {"com.example.demo"}, nameGenerator = UniqueNameGenerator.class)
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
注:
@SpringBootApplication=@Configuration+@EnableAutoConfiguration+@ComponentScan
所以,当@SpringBootApplication和@ComponentScan注解共存时,@SpringBootApplication注解的扫描的作用将会失效,所以此时需要将@SpringBootApplication中扫描包放到@ComponentScan中