SpringBoot之載入自定義配置檔案
阿新 • • 發佈:2019-01-07
SpringBoot預設載入配置檔名為:application.properties和application.yml,如果需要使用自定義的配置檔案,則通過@PropertySource註解指定。
JavaBean:
package org.springboot.model; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource;import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "pet") @Data // 自定義配置檔案路徑 @PropertySource(value = {"classpath:config/pet.properties"}) public class Pet { private String name; private String type; }
pet.properties(./resources/config/pet.properties)
pet.name=haha
pet.type=dog
測試程式碼:
package org.springboot; import org.junit.Test; import org.junit.runner.RunWith; import org.springboot.model.Pet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class DemoApplicationTests { @Autowired Pet pet; // 指定其他配置檔案 @Test public void testPet() { System.out.println(pet); } }
執行結果:
Pet(name=haha, type=dog)