mrdeived:
@PropertySource(値=「myconfig.yml」)との@ConfigurationPropertiesを使用する場合Springbootは、オブジェクトに私のプロパティをシリアル化しません。
私はapplication.ymlでこれと同じ設定を入れて、@PropertySource(値=「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
エブラヒムPasbani:
あなたはジャクソン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;