在Springboot中,如何在使用@ConfigurationProperties和@PropertySource时将属性序列化为对象?

时间:2019-05-29 20:06:47

标签: java spring-boot yaml

在将@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

2 个答案:

答案 0 :(得分:2)

据我所知,无法使用@PropertySource加载YAML属性。由于不确定该问题是否已经解决,我将进行查找。

[编辑] 显然,它hasn't已修复:

  

无法使用@PropertySource批注来加载YAML文件。   因此,如果您需要以这种方式加载值,则需要使用   属性文件。

答案 1 :(得分:1)

您需要使用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;