Spring boot @PropertySource不会自动将字符串属性绑定到枚举?
在使用springboot 1.4的集成测试中,我们使用Spring boot @PropertySource不会自动将字符串属性绑定到枚举?,spring-boot,Spring Boot,在使用springboot 1.4的集成测试中,我们使用 @ConfigurationProperties(locations = "classpath:test.yml") 使用“位置”属性。这是将字符串属性自动映射到枚举。但是从springboot 1.5开始,locations属性被删除 作为一种解决方法,我使用@PropertySource,但它不支持yaml文件。因此,我使用工厂类将yaml转换为java.util.properites。但我面临的问题是,字符串属性不能自动绑定到枚举
@ConfigurationProperties(locations = "classpath:test.yml")
使用“位置”属性。这是将字符串属性自动映射到枚举。但是从springboot 1.5开始,locations属性被删除
作为一种解决方法,我使用@PropertySource,但它不支持yaml文件。因此,我使用工厂类将yaml转换为java.util.properites。但我面临的问题是,字符串属性不能自动绑定到枚举
有什么好的解决办法吗 您可以将yaml文件映射到配置类
application.yml文件的相对路径是/myApplication/src/main/resources/application.yml
Spring应用程序将第一个配置文件作为默认配置文件,除非Spring应用程序中另有声明
YAML文件
将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
@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());
}
}