Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a spring boot project, how to load application.yaml into Java Properties

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?

like image 913
Hollando Romi Avatar asked May 05 '17 04:05

Hollando Romi


People also ask

Can we use application properties and application Yml together in same Spring Boot project?

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.

How does Spring Boot load application properties?

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.


1 Answers

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.

like image 171
g00glen00b Avatar answered Oct 29 '22 22:10

g00glen00b