Spring boot configuration properties example

The Spring boot configuration properties example shows you how to use @ConfigurationProperties annotation loading the entire file into a object easily. Beside, we also show you the JSR-303 bean validation that @ConfigurationProperties annotation supports in a Spring application. This example will introduce about the @Value annotation then we will get the right way to use @Value annotation or @ConfigurationProperties annotation in your application.

Other interesting posts you may like

Let’s begin:

Using @Value and @ConfigurationProperties annotation

For example, we have a simple property file named system.properties:

We can use the @Value annotation to inject the property value one by one, this is good option for simple structure property file.

In case, using @ConfigurationProperties annotation:

Using @ConfigurationProperties for the Complex Properties file
The @ConfigurationProperties annotation supports both .properties file and YAML file.
For example, we have a complex structure property file named application.properties, below

or we can have also the equilvent in YAML named application.yml, below

Next, create a bean which is annotated with @ConfigurationProperties annotation, like this:

Create Spring Boot Application
In this Spring boot configuration properties example. Our Spring Boot Application class is simple like this:

Create web controller
In this Spring boot configuration properties example, we create a controller to see how @Value and @ConfigurationProperties annotations work perfectly:

Run the Spring Boot Web Application: Don’t forget go to the project directory and run the command line mvn spring-boot:run. Then access controller via url http://localhost:8080/, review the output screen:

Spring boot configuration properties example

@ConfigurationProperties Validation
The @ConfigurationProperties annotation also supports JSR-303 bean validation – javax.validation, for example:

Now, we try to run the command line mvn spring-boot:run to start Spring Boot Application again. The console will print the error like this:

That’s all on the Spring boot configuration properties example.

References
ConfigurationProperties Docs
JSR 303: Bean Validation

Download complete source code, click link below

spring-boot-configuration-properties-example.zip (8 downloads)

One thought on “Spring boot configuration properties example

Leave a Comment

*

Please share it if you found this useful
Hide Buttons