![](/img/trans.png)
[英]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.