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

  • 相关阅读:
    框架和库的区别
    象棋中常用的最小值最大值算法及剪枝算法
    cocos2dx 3.x中的渲染机制
    用vs2013编译lua源码方法
    VS中设置#define _CRT_SECURE_NO_WARNINGS的两种方式
    lua编程基础
    VS2013中如何更改主题颜色(深色)和恢复默认的窗口布局
    (二)识别NAND Flash Nor Flash
    Linux设备驱动之Ioctl控制
    linux驱动程序中的并发控制
  • 原文地址:https://www.cnblogs.com/jadening/p/14020947.html
Copyright © 2011-2022 走看看