@PropertySource不会自动将字符串属性绑定到枚举吗?

时间:2019-03-17 02:49:57

标签: spring-boot

在使用springboot 1.4的集成测试中,我们使用了

@ConfigurationProperties(locations = "classpath:test.yml")

具有locations属性。这是将字符串属性自动映射为枚举。但是从springboot 1.5开始,locations属性被删除。

作为一种解决方法,我正在使用@PropertySource,但这不支持yaml文件。因此,我正在使用工厂类将Yaml转换为java.util.properites。但是我遇到了问题,字符串属性没有自动绑定到枚举。

有什么好的解决方案吗?

1 个答案:

答案 0 :(得分:1)

您可以将 yaml 文件映射到配置类

application.yml 文件的相对路径为 /myApplication/src/main/resources/application.yml。

除非在Spring应用程序中另行声明,否则Spring应用程序将第一个配置文件作为默认配置文件。

YAML文件

spring:
    profiles: test
name: test-YAML
environment: test
servers: 
    - www.abc.test.com
    - www.xyz.test.com

---
spring:
    profiles: prod
name: prod-YAML
environment: production
servers: 
    - www.abc.com
    - www.xyz.com

将YAML绑定到配置类

要从属性文件中加载一组相关属性,我们将创建一个bean类:

Configuration
@EnableConfigurationProperties
@ConfigurationProperties
public class YAMLConfig {

    private String name;
    private String environment;
    private List<String> servers = new ArrayList<>();

    // standard getters and setters

}

此处使用的注释是:

@Configuration marks the class as a source of bean definitions
@ConfigurationProperties binds and validates the external configurations to a configuration class
@EnableConfigurationProperties this annotation is used to enable @ConfigurationProperties annotated beans in the Spring application

用法:

@SpringBootApplication
public class MyApplication implements CommandLineRunner {
 
    @Autowired
    private YAMLConfig myConfig;
 
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MyApplication.class);
        app.run();
    }
 
    public void run(String... args) throws Exception {
        System.out.println("using environment: " + myConfig.getEnvironment());
        System.out.println("name: " + myConfig.getName());
        System.out.println("servers: " + myConfig.getServers());
    }
}