[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();
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM