zoukankan      html  css  js  c++  java
  • 自定义个Bean名称生成策略, 解决不同包下同名类问题/AnnotationBeanNameGenerator

    一.写一个类继承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

  • 相关阅读:
    curl 空格和转义符
    supervisor
    pandas 小笔记
    bert 进行文本相似度计算
    认股权证的会计处理
    企业所得税汇算清缴
    调整事项与非调整事项的区别
    centos 挂载windows 2003 smb
    如何获得带转义的json内容
    安装了vs2019 编译node-sass node-gyp 找不到编译器的解决方法
  • 原文地址:https://www.cnblogs.com/jadening/p/14020947.html
Copyright © 2011-2022 走看看