[SpringBoot] 经过spring.factory文件来加载第三方的bean

    在springboot的开发过程当中,咱们常常须要加载一些bean,若是bean使咱们本身写的类,那很好办,加个@Component注解就搞定了,而后过程启动会扫描启动类所在的包及其子包,若是咱们须要的bean不在本身的包里面,在第三方包怎么办?这里介绍一个使用spring.factories文件的方法
    指望工程启动的时候就加载这个bean到容器,咱们的包是提供给其余人使用的,其余工程的启动了类所在的路径不能覆盖这个bean所在的包路径,经过ComponouneScan扫描太麻烦了,并且需求是工程启动后就加载bean,能够这样作:spring


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

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

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

@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(); } }
相关文章
相关标签/搜索