В Springboot, как сериализовать свойства в объекты при использовании @ConfigurationProperties и @PropertySource? - PullRequest
2 голосов
/ 29 мая 2019

При использовании @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 ]

2 голосов
/ 29 мая 2019

Насколько мне известно, свойства YAML не могут быть загружены с помощью @PropertySource.Я посмотрю его, так как не уверен, что проблема была решена за это время.

[править] Очевидно, что не был исправлен:

Файлы YAML не могут быть загружены с помощью аннотации @PropertySource.Таким образом, в случае, если вам нужно загрузить значения таким образом, вам нужно использовать файл свойств.

1 голос
/ 30 мая 2019

Вам нужно использовать зависимость Джексона Ямля.

//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;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...