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();
        }
    }
  • 相关阅读:
    JavaScript 简介
    HTML 标签列表
    HTML5 是什么
    初识HTML5
    Conda 环境增删改查导出导入
    Windows 下安装 CGAL 并验证安装
    3D 点云数据集整理分析
    内网穿透
    SSH 免密登录
    串口、COM口、TTL、RS-232、RS-485区别详解
  • 原文地址:https://www.cnblogs.com/aaron911/p/11282364.html
Copyright © 2011-2022 走看看