Spring boot @ConfigurationProperties

In this tutorial, we are going to see about Spring boot @ConfigurationProperties annotation.

Spring boot @ConfigurationProperties allows you to map properties values with java object easily.

Let’s first see the normal mapping first. Let’s say you have properties file below.

application.properties

You can access above property file as below.

So, you can use @Value to get property value from application.properties but it might be tedious to use @Value everywhere,Spring boot provides @ConfigurationProperties to map properties value to java Object.

Let’s understand with the help of example.

Step 1: Create a dynamic web project using maven in eclipse named “SpringBootHelloWorldExample”.

Maven dependencies:

Step 2: Change pom.xml as below:

step 3: Create a package named "org.arpit.java2blog" and class named ServerDetails

step 4: Make changes to application.properties to add below properties.

step 5: Create Spring boot main class.

As you can see, we have used @Autowired to inject ServerDetails to SpringBootExample.

Step 6: Run the application.

When you run above example, you will get below output.

. ____ _ __ _ _
/\\ / ___’_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | ‘_ | ‘_| | ‘_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
‘ |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.3.RELEASE)

2018-07-14 23:53:47.766 INFO 67832 — [ main] org.arpit.java2blog.SpringBootExample : Starting SpringBootExample on apples-MacBook-Air.local with PID 67832 (/Users/apple/Downloads/SpringBootConfigurationPropertiesExample/target/classes started by apple in /Users/apple/Downloads/SpringBootConfigurationPropertiesExample)
2018-07-14 23:53:47.774 INFO 67832 — [ main] org.arpit.java2blog.SpringBootExample : No active profile set, falling back to default profiles: default
2018-07-14 23:53:47.901 INFO 67832 — [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.spring[email protected]429bd883: startup date [Sat Jul 14 23:53:47 IST 2018]; root of context hierarchy
Server Details{name=’amazonEc2′, url=’dummy.xyz.com’, port='[8080, 8081]’, username=’admin’, password=’admin123′}
2018-07-14 23:53:49.000 INFO 67832 — [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-07-14 23:53:49.024 INFO 67832 — [ main] org.arpit.java2blog.SpringBootExample : Started SpringBootExample in 2.252 seconds (JVM running for 3.406)
2018-07-14 23:53:49.028 INFO 67832 — [ Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.spring[email protected]429bd883: startup date [Sat Jul 14 23:53:47 IST 2018]; root of context hierarchy
2018-07-14 23:53:49.030 INFO 67832 — [ Thread-2] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown

Here is the picture which will help you understand @ConfigurationProperties better.

Relaxed binding

One of the interesting feature of Spring boot is relaxed binding.
for com.server.application.username, below are valid spring boot bindings.

  • com.server.application.user_name(with _)
  • com.server.application.user-name(with -)
  • com.server.application.USER_NAME(with uppercase)

Custom property file

You can use custom property as well instead of application.property using @PropertySource annotation.

Validation

We can use JSR-303 Validation API to validate properties.You need to add below dependency.

For example:
Let’s say you want to restrict username from 5 to 8 characters, you can use @Length annotaton as below.

If you change userName to adam

You will get below validation error.

Property:.com.server.application.username
Value: adam
Reason: length must be between 5 and 8

That’s all about Spring boot @ConfigurationProperties.


import_contacts

You may also like:

Related Posts

  • 11 January

    Spring boot JDBC example

    Table of ContentsTools usedProject StructureCreate new Spring boot projectMaven configurationConfigure datasource in Application.propertiesCreate database tableCreate model classCreate Repository interface and implementationCreate service interface and implementationCreate Application classRun the applicationVerify database outputGithub Source code In this post, we will see Spring boot JDBC example. As we already know Spring boot does lot of auto configurations which […]

  • 02 January

    Spring boot devtools tutorial

    Table of ContentsOverviewJRebelIntroduction to Spring Boot DevToolsAdding Devtools to your projectSpring Boot DevTools FeaturesProperty DefaultsLoggingCachingAutomatic RestartLive ReloadGlobal SettingsRemote ApplicationsFile System WatchersConclusion In this post, we’ll be looking up what does spring has to offer for developer experience. Overview Using IDEs like Eclipse, Spring Tool Suite, Intellij Idea a typical development setup includes an application code […]

  • 26 December

    Spring boot H2 Database example

    Table of ContentsWhat is H2 database?Tools usedGithub Source code:Project StructureCreate new Spring boot projectMaven configurationH2 database configurationOverride H2 databse defaultsModelRepositoryServiceControllerSpring boot main fileRun the applicationTest the applicationCreate movie objectGet all movie objectsDelete movie id 3 In this post, we are going to see how to create Spring boot application integrating with H2 database. What is […]

  • 22 December

    Spring Boot CrudRepository

    Table of ContentsTools usedProject Structure:Wiring up MongoDBThe Repository ClassThe Save methodThe User Entity ClassBringing the UserDao and CrudRepository togetherServiceControllerApplication classRunning the code sampleConclusionSource code In this post, we’ll be looking up how to create and use Spring Boot CrudRepository. SpringBoot CrudRepository provides sophisticated CRUD functionality for the type of entity you want to be managed.This […]

  • 10 April

    Difference between Spring and Spring boot

    Table of ContentsSpring frameworkSpring bootAdvantages of Spring BootSpring vs Spring boot In this post, we will see difference between Spring and Spring boot. If you have followed spring project over time, you might have noticed it has become increasingly complex. If you want to create a spring application, you still need to put a lot […]

  • 17 September

    Spring Boot SOAP Web service Example

    Table of ContentsTools usedProject structureAdd wsdl4j dependencyXSD file to define domainGenerate domain classes based on XSDCreate Book repository with dummy dataDefine Book service endpointDefine web service configurationRun the applicatonTest WSDL URLTest Spring soap web serviceSource code In this post, we will see how to create soap web services with Spring boot. We will create contract […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.