Application Configuration with Spring Boot


This guide will introduce you to the various application configuration options that are present in Spring Boot. You will also learn how to create custom configuration for an application.

You will learn

  • What is application configuration?
  • Why do we need application configuration?
  • What is application.properties?
  • What are some of the important things that can customized in application.properties?
  • How do you externalize configuration using Spring Boot?
  • How can you add custom application properties using Spring Boot?
  • What is @ConfigurationProperties?
  • What are the advantages of using @ConfigurationProperties?

10 Step Reference Courses

Need for Application Configuration

Configuration for applications vary from one environment to another

  • You would want to connect to a different database or queues
  • You would want to connect with different services
  • You would want to configure less logging in production
  • You might want to have different custom configuration

Application Configuration with Spring Boot application.properties

Spring Boot allows you to configure your application configuration using a file named application.properties

application.properties can reside anywhere in the classpath of the application.

In application.properties, we can use the “logging.level” prefix to set logging levels.

logging.level.some.package.path=DEBUG
logging.level.some.other.package.path=ERROR

You can configure a log file by using logging.file property in application.properties. The logging here would be in addition to the logging in console.

logging.file=\path_to\logfile.log

You can also configure the port to run the server on using server.port

server.port = 9080

For complete list of options refer spring documentation - https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

In this guide, we will create three services using proper URIs and HTTP methods:

Project Code Structure

Following screenshot shows the structure of the project we will create. Image

A few details:

  • SpringBootTutorialBasicsConfigurationApplication.java - The Spring Boot Application class generated with Spring Initializer. This class acts as the launching point for application.
  • pom.xml - Contains all the dependencies needed to build this project.
  • BasicConfiguration.java - We will use this component to define application configuration using @ConfigurationProperties
  • WelcomeResource.java - Example of a resource using @Value
  • application.properties - Configuration for application

Tools you will need

  • Maven 3.0+ is your build tool
  • Your favorite IDE. We use Eclipse.
  • JDK 1.8+

Complete Maven Project With Code Examples

Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics-configuration

Bootstrapping with Spring Initializr

Spring Initializr http://start.spring.io/ is great tool to bootstrap your Spring Boot projects.

Image

Image

As shown in the image above, following steps have to be done

  • Launch Spring Initializr and choose the following
    • Choose com.in28minutes.springboot.tutorial.basics.application.configuration as Group
    • Choose spring-boot-tutorial-basics-configuration as Artifact
    • Choose following dependencies
      • Web
      • DevTools
  • Click Generate Project.
  • Import the project into Eclipse. File -> Import -> Existing Maven Project.

Application Configuration using @Value

Let’s create a very simple example.

@RestController
public class WelcomeResource {

	@Value("${welcome.message}")
	private String welcomeMessage;

	@GetMapping("/welcome")
	public String retrieveWelcomeMessage() {
		// Complex Method
		return welcomeMessage;
	}
}

Notes

  • @Value("${welcome.message}") private String welcomeMessage; - Pick up the value for welcome.message from application configuration and assign it to this member variable.
  • @GetMapping("/welcome") public String retrieveWelcomeMessage() - Expose a simple service using the configuration

Let’s configure a value for welcome message in the application.properties.

welcome.message=Welcome message from property file! Welcome to in28Minutes

When you launch http://localhost:8080/welcome, you would see a page with this message

Welcome message from property file! Welcome to in28Minutes

We can make the application.properties more creative by using other properties as variables too.

app.name=in28Minutes
welcome.message=Welcome message from property file! Welcome to ${app.name}

Spring Boot provides different ways of configuring your property values.

  • You can send in a program argument
    • –welcome.message=”SomethingElse”
  • You can use a different file as property file
    • –spring.config.location=classpath:/default.properties
  • You can configure an environment variable

@Value is the basic approach for application configuration using Spring.

Application Configuration using Type-safe Configuration Properties

The problem with @Value is that you would have your configuration values distributed through out your application. A better option would be to have a centralized approach.

You can define a configuration component using @ConfigurationProperties.

@Component
@ConfigurationProperties("basic")
public class BasicConfiguration {
    private boolean value;
    private String message;
    private int number;

    public boolean isValue() {
        return value;
    }

    public void setValue(boolean value) {
        this.value = value;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

}

Notes:

  • @Component @ConfigurationProperties("basic") - Defines that this java bean contains configuration properties. All property names will start with basic..
  • private boolean value - A boolean value. Can be configured as basic.value.
  • private String message - A String value. Can be configured as basic.message.

We would need to use the BasicConfiguration in a service to expose the values

@Autowired
private BasicConfiguration configuration;

@RequestMapping("/dynamic-configuration")
public Map dynamicConfiguration() {
    // Not the best practice to use a map to store differnt types!
    Map map = new HashMap();
    map.put("message", configuration.getMessage());
    map.put("number", configuration.getNumber());
    map.put("key", configuration.isValue());
    return map;
}

Notes

  • @Autowired private BasicConfiguration configuration - Its very easy to use BasicConfiguration. Autowire it in when ever you need the value for a property from it.
  • @RequestMapping("/dynamic-configuration") public Map dynamicConfiguration() { - Define a simple service to expose the configured values.

The values can be configured in application.properties

basic.value: true
basic.message: Dynamic Message
basic.number: 100

When you browse to http://localhost:8080/dynamic-configuration, you see the following response.

{"number":100,"message":"Dynamic Message","key":true}

Understand Type Safety

@ConfigurationProperties is type safe. If you configure any property with a value of an invalid type, the application fails at startup.

Below snippet shows the log when basic.number is assigned a non numberic value.

***************************
APPLICATION FAILED TO START
***************************

Description:

Binding to target [email protected]8545 failed:

    Property: basic.number
    Value: ABC
    Reason: Failed to convert property value of type [java.lang.String] to required type [int] for property 'number'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [int]


Action:

Update your application's configuration

Congratulations! You are reading an article from a series of 50+ articles on Spring, Spring Boot , Hibernate, Full Stack, Cloud and Microservices. We also have 20+ projects on our Github repository. For the complete series of 50+ articles and code examples, click here.

Join 300,000 Learners!

Learn Spring Boot in 10 Steps - FREE Course

Next Steps

Image](https://www.udemy.com/full-stack-application-with-spring-boot-and-react/?couponCode=SBT-2019){:target=”_blank”}

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Complete Code Example

/pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.in28minutes.springboot.tutorial.basics.application.configuration</groupId>
	<artifactId>spring-boot-tutorial-basics-configuration</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>spring-boot-tutorial-basics-configuration</name>
	<description>Spring Boot Tutorial - Application Configuration with Profiles and YAML</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

	<repositories>
		<repository>
			<id>spring-snapshots</id>
			<name>Spring Snapshots</name>
			<url>https://repo.spring.io/snapshot</url>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>

	<pluginRepositories>
		<pluginRepository>
			<id>spring-snapshots</id>
			<name>Spring Snapshots</name>
			<url>https://repo.spring.io/snapshot</url>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</pluginRepository>
		<pluginRepository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</pluginRepository>
	</pluginRepositories>


</project>

/src/main/java/com/in28minutes/springboot/tutorial/basics/application/configuration/BasicConfiguration.java

package com.in28minutes.springboot.tutorial.basics.application.configuration;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties("basic")
public class BasicConfiguration {
	private boolean value;
	private String message;
	private int number;

	public boolean isValue() {
		return value;
	}

	public void setValue(boolean value) {
		this.value = value;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public int getNumber() {
		return number;
	}

	public void setNumber(int number) {
		this.number = number;
	}

}

/src/main/java/com/in28minutes/springboot/tutorial/basics/application/configuration/SpringBootTutorialBasicsConfigurationApplication.java

package com.in28minutes.springboot.tutorial.basics.application.configuration;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;

@SpringBootApplication
public class SpringBootTutorialBasicsConfigurationApplication {

	public static void main(String[] args) {
		ApplicationContext applicationContext = SpringApplication
				.run(SpringBootTutorialBasicsConfigurationApplication.class, args);

		for (String name : applicationContext.getBeanDefinitionNames()) {
			System.out.println(name);
		}
	}
}

/src/main/java/com/in28minutes/springboot/tutorial/basics/application/configuration/WelcomeResource.java

package com.in28minutes.springboot.tutorial.basics.application.configuration;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WelcomeResource {

	@Value("${welcome.message}")
	private String welcomeMessage;

	@GetMapping("/welcome")
	public String retrieveWelcomeMessage() {
		// Complex Method
		return welcomeMessage;
	}

	@Autowired
	private BasicConfiguration configuration;

	@RequestMapping("/dynamic-configuration")
	public Map<String, Object> dynamicConfiguration() {
		// Not the best practice to use a map to store differnt types!
		Map<String, Object> map = new HashMap<>();
		map.put("message", configuration.getMessage());
		map.put("number", configuration.getNumber());
		map.put("key", configuration.isValue());
		return map;
	}
}

/src/main/resources/application.properties

logging.level.org.springframework.web.servlet: DEBUG
app.name=in28Minutes
welcome.message=Welcome message from property file! Welcome to ${app.name}

basic.value: true
basic.message: Dynamic Message
basic.number: 100

/src/test/java/com/in28minutes/springboot/tutorial/basics/application/configuration/SpringBootTutorialBasicsConfigurationApplicationTests.java

package com.in28minutes.springboot.tutorial.basics.application.configuration;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootTutorialBasicsConfigurationApplicationTests {

	@Test
	public void contextLoads() {
	}

}

Related Posts

Spring Boot Tutorials for Beginners

At in28Minutes, we are creating a number of tutorials with videos, articles & courses on Spring Boot for Beginners and Experienced Developers. This resources will help you learn and gain expertise at Spring Boot.

Spring and Spring Boot Video Tutorials for Beginners

At in28Minutes, we are creating a number of tutorials with videos, articles & courses on Spring Boot for Beginners and Experienced Developers. Here's a list of video tutorials and courses for you

What is an In Memory Database?

In this article, we understand what the term "In-Memory Database" actually means. We see what scenarios they can be used, and why they are important.

What is an Embedded Server?

In this article, we focus in exploring what an embedded server is, and how they help make application deployment simpler.

Java Tools and Frameworks - Introduction To Maven

In this article, we experience a brief introduction to Maven, and will see how it helps in managing your project dependencies.

Five Tools To Learn as a Java Developer

In this article, we introduce you to five great tools that we recommend every Java Developer to learn.

Five Languages To Learn as a Java Programmer

As a programmer, you want to explore new things. Learning a new language gives you a different perspective when solving problems. What are the 5 languages that a Java developer should explore?

Five Great Frameworks To Try for Java Programmers

As a programmer you want to explore new languages and frameworks. What would be the best frameworks to explore in 2019 for Java Programmers?

Unit Testing Best Practices - with Java and Junit Examples

Unit Testing is often underrated. As far as I am concerned, having good unit tests seperates good projects from bad. In this article, let's look at unit testing best practices in depth. We use examples from Java and JUnit to illustrate the concepts. However, the best practices are applicable irrespective of the programming language used.

Programming Basics - Unit Testing - What Is Mocking?

Mocking is an important concept that is made use of, when writing unit tests. In this article, we explore what mocking is all about, and explore some of the popular Java mocking frameworks in use.