springboot家在配置問題

配置文件位置

1、默認位置

springboot默認配置文件名稱爲application.properties,SpringApplication將從一下位置將配置文件加載到spring Environment中

  1. 當前目錄下的/config子目錄
  2. 當前目錄
  3. 一個classpath下的/config子目錄
  4. classpath根路徑

這個順序按優先級進行加載,如果有多個同名的application.properties文件,最上面的覆蓋最下面的。

2、自定義位置

如果需要自定義文件名或者位置,則在啓動springboot時傳入參數spring.config.location

3、動態加載外部配置

  1. 實現EnvironmentPostProcessor接口,並配置到容器當中
    @Component
    public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {
        @Override
        public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication springApplication) {
            try (InputStream stream = new FileInputStream("d:\\jdbc.properties")){
                Properties properties = new Properties();
                properties.load(stream);
                PropertiesPropertySource source = new PropertiesPropertySource("jdbc",properties);
                configurableEnvironment.getPropertySources().addLast(source);
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

     

  2. 在classpath下的META-INF下加一個spring.factories文件,在文件中配置
    org.springframework.boot.env.EnvironmentPostProcessor=com.xxx.MyEnvironmentPostProcessor

     

這樣再啓動springboot是,springboot會根據spring.factories文件中的配置找到EnvironmentPostProcessor的實現類,執行

postProcessEnvironment方法,將配置文件加載到系統當中。

將配置文件中的數據加載到類中

  1. @Component和@Value("${"xxx"}")

    @Component
    public class Configurations {
        
        @Value("${test.name}")
        private String name;
    
        @Value("${test.age}")
        private String age;
    
        @Value("${test.tel}")
        private Long tel;
    
        // getter and setter
    }

     

@ConfigurationProperties(prefix = "test")

@Component
@ConfigurationProperties(prefix = "test")
public class Configuration {

    private String name;

    private String age;

    private Long tel;

    // setter getter
}

將配置文件中已test開頭的這幾個屬性加載到類中,當然還可以制定家在哪個配置文件

@ConfigurationProperties(prefix = "test", locations = "classpath:xxxx.properties")

根據環境不同加載不同配置,家在多個配置文件

  1. profiles
    1. 不同環境下的配置文件名稱application-{profile}.properties
      1. application-dev.properties
      2. application-test.properties
      3. application.pro.properties
    2. 在默認配置文件中配置spring.profiles.active={profile},就可以加載不同的配置文件了,比如spring.profiles.active=dev就是加載application-dev.properties文件。
  2. 通過啓動參數加載不同的配置文件--spring.profiles.active=test
  3. 加再多個配置文件:spring.profiles.active=dev,test

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章