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?
Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use properties files, YAML files, environment variables, and command-line arguments to externalize configuration.
Spring Boot loads the application. properties file automatically from the project classpath. All you have to do is to create a new file under the src/main/resources directory. The application.
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
@Valueannotation, accessed via Spring’sEnvironmentabstraction or bound to structured objects via@ConfigurationProperties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With