SpringBoot引入其他配置文件


  1. @PropertySource
    • 屬性

1.value為要加載的文件,可以是多個,當以classpath開頭時,程序會自動到classpath中讀取,當以file開頭時,會加載外部的文件
2.name是表示要加載文件的名稱,這里要加載的配置文件必須是 唯一的不能是多個
3.encoding,設置編碼,我們一般用utf-8
4.ignoreResourceNotFound,這個屬性的意思是當加載的配置文件不存在時,是否報錯默認false,當為true時表示文件不存在不報錯,為false時表示文件不存在報錯

    • 獲取單個參數

      使用@Value()注解獲取:@Value("${參數名}“”)

    • 批量獲取參數 (@ConfigurationProperties)

語法:@ConfiggurationProperties(prefix="參數前綴')

  1. @PropertySources
    • 屬性

      value:PropertySource[] value(),是一個PropertySource的集合。

      語法:@PropertySources({ @PropertySource("classpath:配置文件名"),@PropertySource("classpath:配置文件名") })

    • 獲取單個參數

      使用@Value()注解獲取:@Value("${參數名}“”)

    • 批量獲取參數(@ConfigurationProperties)

      語法:@ConfiggurationProperties(prefix="參數前綴')

    • 代碼示范
@Configuration
@PropertySources({
        @PropertySource("classpath:MongoDB.properties"),
        @PropertySource("classpath:Redis.properties"),
        @PropertySource("classpath:Mysql.properties")
})
@ConfigurationProperties(prefix = "data")
public class DemoConfig {
    @Value("mysql")
    private String mysql;
    @Value("redis")
    private String redis;
    @Value("mongodb")
    private String mongodb;
    @Bean
    public User user(){
        return new User(mysql,mysql,mongodb);
    }
}

 


免責聲明!

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



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