[英]Reading multiple properties files with @PropertySource (SpringBoot)using wildcard character
[英]In Springboot, how to serialize properties into objects when using @ConfigurationProperties and @PropertySource?
將 @ConfigurationProperties 與 @PropertySource(value = "myconfig.yml") 一起使用時,Springboot 不會將我的屬性序列化為對象
如果我將相同的配置放在 application.yml 中並刪除 @PropertySource(value = "myconfig.yml"),則它可以工作
---
testPrefix.simpleProperty: my.property.haha
testPrefix.complexProperties:
-
firstName: 'Clark'
lastName: 'Ken'
-
firstName: 'Roger'
lastName: 'Federer'
@Configuration
@ConfigurationProperties(prefix = "testPrefix")
@PropertySource(value = "testConfigFile.yml")
public class MyTestProperties {
private String simpleProperty;
private List<Person> complexProperties;
getters
setters
@SpringBootApplication
public class App implements CommandLineRunner {
MyTestProperties myProperties;
@Autowired
public App(MyTestProperties properties) {
this.properties = properties;
}
public static void main(String[] args) {
SpringApplication app = new SpringApplication((App.class));
app.run(args);
}
@Override
public void run(String... args) throws Exception {
System.out.println(myProperties.getSimpleProperty());
myProperties.getComplexProperties.stream.forEach(System.out::println));
}
}
輸出:
my.property.haha
據我所知,無法使用@PropertySource
加載 YAML 屬性。 我會查一下,因為我不確定在此期間問題是否已解決。
[編輯] 顯然,它還沒有被修復:
無法使用 @PropertySource 注釋加載 YAML 文件。 因此,如果您需要以這種方式加載值,則需要使用屬性文件。
您需要使用 jackson yaml 依賴項。
//pom.xml
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
然后創建一個工廠類來加載 yaml 文件作為屬性源。
//YamlPropertySourceFactory.java
import java.io.IOException;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String s,
EncodedResource encodedResource) throws IOException {
YamlPropertiesFactoryBean bean = new YamlPropertiesFactoryBean();
bean.setResources(encodedResource.getResource());
return new PropertiesPropertySource(
s != null ? s : encodedResource.getResource().getFilename(),
bean.getObject());
}
}
然后像這樣使用PropertySource
注釋。
@PropertySource(factory = YamlPropertySourceFactory.class, value = "testConfigFile.yml")
public class MyTestProperties {
private String simpleProperty;
private List<Person> complexProperties;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.