zoukankan      html  css  js  c++  java
  • [SpringBoot] 通过spring.factory文件来加载第三方的bean

        在springboot的开发过程中,我们经常需要加载一些bean,如果bean使我们自己写的类,那很好办,加个@Component注解就搞定了,然后过程启动会扫描启动类所在的包及其子包,如果我们需要的bean不在自己的包里面,在第三方包怎么办?这里介绍一个使用spring.factories文件的方法
        期望工程启动的时候就加载这个bean到容器,我们的包是提供给其他人使用的,其他工程的启动了类所在的路径不能覆盖这个bean所在的包路径,通过ComponouneScan扫描太麻烦了,而且需求是工程启动后就加载bean,可以这样做:


      在包下面的resources下面新建文件/META-INF/spring.factories文件,里面写上下面的内容

    org.springframework.boot.autoconfigure.EnableAutoConfiguration=cn.aaron911.shield.ShieldAutoConfiguration

      右边是你的一个类,然后在这个类里面写入:

    @Configuration
    @ConditionalOnBean(annotation = EnableShieldDefence.class)
    @EnableConfigurationProperties(ShieldProperties.class)
    public class ShieldAutoConfiguration {
    
        private static final Logger log = LoggerFactory.getLogger(ShieldAutoConfiguration.class);
    
        @Autowired
        private ShieldProperties properties;
    
        @PostConstruct
        public void init() {
            log.info("You'll be safe with shield... ");
            log.info(properties.toString());
        }
    
        @Bean
        @ConditionalOnMissingBean(name = {"shieldProcessor"})
        public ShieldProcessor shieldProcessor() {
            return new ShieldProcessorDefence();
        }
    
        @Bean(name = "shieldCache")
        public Cache shieldCache() {
            CacheType type = properties.getCacheType();
            if (type == CacheType.REDIS) {
                return new RedisCache();
            }
            return new ConcurrentHashMapCache();
        }
    }
  • 相关阅读:
    静态方法、类方法和属性方法
    类的私有属性和私有方法
    JMeter-正则表达式(取出银行卡号后4位)
    JMeter连接MySQL数据库
    解决chrome提示您的连接不是私密连接的方法
    python安装appium模块
    mac中的word内容丢失
    有些事一旦开始就停不下来了
    Python接口测试-以&连接拼接字典数据(get中url请求数据)
    Python接口测试-模块引用与映射
  • 原文地址:https://www.cnblogs.com/aaron911/p/11282364.html
Copyright © 2011-2022 走看看