In a spring boot project, how to load application.yaml into Java Properties
java, spring-boot, yaml
Solution
By default, Spring already puts all those application properties in its environment which is a wrapper of `Properties`, for example:
@Autowired
private Environment environment;
public void stuff() {
environment.getProperty("myPro.prop1");
environment.getProperty("myPro.prop2");
}
However, if you just want to use the values, you can always use the `@Value` annotation, for example:
@Value("${myPro.prop1}")
private String prop1;
@Value("${myPro.prop2}")
private String prop2;
Lastly, if you really want a `Properties` object with just everything in `myPro`, you can create the following bean:
@ConfigurationProperties(prefix = "myPro")
@Bean
public Properties myProperties() {
return new Properties();
}
Now you can autowire the properties and use them:
@Autowired
@Qualifier("myProperties")
private Properties myProperties;
public void stuff() {
myProperties.getProperty("prop1");
myProperties.getProperty("prop2");
}
In this case, you don't necessarily have to bind it to `Properties`, but you could use a custom POJO as well as long as it has a fieldname `prop1` and another fieldname `prop2`.
These three options are also listed in the documentation:
Property values can be injected directly into your beans using the `@Value` annotation, accessed via Spring’s `Environment` abstraction or bound to structured objects via `@ConfigurationProperties`.
Problem
If I have the following properties in application.yaml: ``` myPro: prop1: prop1value prop2: prop2value .... ``` Is there a way to load this into a Java `Properties` object?