Getting started with Spring Boot, Part 11 Configuring Spring applications by Properties
Properties are key-value pairs that can be used to configure Spring applications. The easiest way to specify properties is a Properties file. We will take a closer look at this in the following.
With a Properties file, Spring applications are relatively easy to configure.
(Image: Spring.io)
In a Properties file, key and value are simply separated by an equal sign. In Spring Boot, the configuration file is called by Convention application.properties and is src / main / resources. Typical examples are setting the port or root context under which the application is accessible:
server.port=8081
server.servlet.context-path=/myapp
With this information in the application.properties file is the application under http://localhost:8081/myapp accessible. Spring Boot finds and uses these Properties automatically.
With the help of the dot notation, related properties can be grouped by a prefix. In the following example, url, user name and password a database connection under the prefix database in sum:
database.url=jdbc:postgresql:/localhost:5432/instance
database.username=postgres
database.password=8dHj7Nds
Properties can alternatively be stored in YAML format. The file is then located in the same place, but application.yml. The same database connection – configured in YAML – looks like this:
database:
url: jdbc:postgresql:/localhost:5432/instance
username: postgres
password: 8dHj7Nds
The prefix is pulled out and does not need to be repeated. By indentation it is specified that url, user name and password to database include. Which of the two variants one uses is a matter of taste. The YAML format is well suited for hierarchically structured properties. It is a bit tidier and less voluminous, but sensitive to false indentations.
Integrating properties with @Value
With the annotation @Value you can use values from the Properties file in the application. For this purpose, you create a variable, annotate it with @Value and specify the name of the property in brackets with a special syntax (“${}”). The following example shows a salutation in application.properties defined:
greeting=Sehr geehrte Damen und Herren
The integration in the Java code looks like this:
@Value("${greeting}")
private String greeting;
The variable greeting here it is of type String, but it can also include primitive data types in the same way. The value is then automatically converted to the data type of the variable :
minAge=16 // application.properties
@Value("${minAge}")
private int minAge;
After the key, you can specify a default value, separated by a colon, if the property does not exist:
@Value("${minAge:18}")
private String minAge;
Since this is a form of injection (field injection), this only works in components or configurations, i.e. classes marked with @Component, @Controller, @Service, @Repository or @Configuration.
The other injection types work the same way, the following code piece shows this using the example of the constructor injection:
@Controller
public class PersonController { private int minAge;
public PersonController(@Value("${minAge}") int minAge) {
this.minAge = minAge;
}
// ...
}
Properties can also be included elsewhere, for example @RequestMapping supports the syntax. The access paths of an application can be made configurable :
mypath=/home // application.properties
@RequestMapping("${mypath}")
public String home() { // ...
return "home";
}
Additional sources: @ PropertySource
That Spring Boot is a properties file from src/main / resources named application.read in properties, is an episode of Spring Boots “Convention over Configuration“-Approach. However, in certain cases it may still be necessary to use a file with a different name.
This is possible with the @PropertySource annotation. In the following example, a file named config.properties involved:
@Controller
@PropertySource("classpath:config.properties")
public class PersonController { @Value("${greeting}")
private String greeting; // ...
}
The file can be read with @Value as described above. However, the @ PropertySource mechanism has a small disadvantage, it does not work with properties in YAML format. In addition, you have to remember that any existing application.properties is additionally read and evaluated.
Mapping entire objects: @ConfigurationProperties
So far, individual config values have been included, but there is also the possibility to map entire objects with config properties. To do this, group the affected properties with a prefix, as was done above for the database connection. All properties start here again with a database:
database.url=jdbc:postgresql:/localhost:5432/instance
database.username=postgres
database.password=8dHj7Nds
To match this, we create a class, in the example it is called DBProperties, which has member variables matching the properties. The class must also be equipped with getters and setters for the variables and annotated with @ConfigurationProperties. The prefix attribute of the annotation @ConfigurationProperties is set to database placed:
@Configuration
@ConfigurationProperties(prefix = "database")
public class DBProperties { private String url;
private String username;
private String password; // Getter und Setter
// ...
}
Thanks to the @Configuration annotation, the class is managed by the Spring container and the variables are automatically filled with the variables defined in the Properties file. DBProperties can then be injected into other classes as usual with @Autowired and used there.
The validation fails here, the application refuses to Start.
(Picture: Koller)
Especially nice to @ConfigurationProperties: The values can be validated with the help of JSR-303. For this purpose, the variables are provided with the desired constraints and the class is annotated with @Validated:
@Configuration
@Validated
@ConfigurationProperties(prefix = "database")
public class DBProperties { @NotBlank
private String url; private String username;
@Size(min = 10, max = 20)
private String password; // Getter und Setter
// ...
}
If the conditions are not met, the start of the application fails. In the next article of the series we look at Spring profiles, properties play a role again.
(ID:47327230)