springboot使用自定義配置檔案
阿新 • • 發佈:2019-02-09
由於高版本的springboot去掉了@configurationProperties中的location引數,然後在網上查了一些資料,總結了以下兩種方法使用自定義的配置檔案:
1. 第一種方法:
(1)在resource目錄下建立測試用的yml配置檔案
myconfig:
test: 123
(2)建立bean檔案
@Component//使用@Configuration也可以 @ConfigurationProperties(prefix = "myconfig")//字首 @PropertySource(value = "classpath:myconfig.yml")//配置檔案路徑 public class MyConfig { @Value("${test}")//需要使用@value註解來注入,否則是null private String test; public String getTest() { return test; } public void setTest(String test) { this.test = test; } }
注:在網上看到的使用方法中,有很多並沒有使用@Value註解,但是在本地測試發現(也嘗試了@EnableConfigurationProperties註解,但是並不好用)如果不在屬性上使用@value註解,總是null
(3)主函式輸出:123@SpringBootApplication public class ConfigApplication implements CommandLineRunner { @Autowired private MyConfig myconfig; public static void main(String[] args) { SpringApplication.run(ConfigApplication.class, args); } @Override public void run(String... strings) throws Exception { System.out.println(myconfig.getTest()); } }
2.第二種方法:
(1)建立YamlPropertySourceFactory繼承PropertySourceFactory
public class YamlPropertySourceFactory implements PropertySourceFactory{ @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { return name != null ? new PropertySourcesLoader().load(resource.getResource(), name, null) : new PropertySourcesLoader().load( resource.getResource(), getNameForResource(resource.getResource()), null); } private static String getNameForResource(Resource resource) { String name = resource.getDescription(); if (!org.springframework.util.StringUtils.hasText(name)) { name = resource.getClass().getSimpleName() + "@" + System.identityHashCode(resource); } return name; } }
(2)指定factory為剛才建立的YamlPropertySourceFactory,用此方法不需要使用@Value即可實現屬性的自動注入
@Component
@ConfigurationProperties(prefix = "myconfig")
@PropertySource(value = "classpath:myconfig.yml",factory=YamlPropertySourceFactory.class)//指定factory
public class MyConfig {
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}