[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();
    }
}
posted @ 2019-08-01 14:39  Mr.Aaron  阅读(3952)  评论(0编辑  收藏  举报