Spring Boot - Configuration

There are many ways to set configuration to a Spring Boot application.

What is Property in Spring Boot

Properties play an important role in almost all applications, and may originate from a variety of sources: properties files, JVM system properties, system environment variables, JNDI, servlet context parameters, ad-hoc Properties objects, Maps, and so on.

Environment is an interface representing the environment in which the current application is running. Spring Boot stores properties in an Environment bean.

Command Line Properties

We can set properties from the command line. Spring Boot will add them to Spring Environment. Command line properties take precedence over the other property sources.

1
java -jar app.jar --server.port=8000

you can ualso use system properties.

1
java -Dserver.port="8000" -jar app.jar

application.properties File

The default Property File is application.properties in src/main/resources folder.

application.properties example

1
2
3
4
spring.datasource.url=jdbc:mysql://localhost:3306/persondb
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

YAML based configuration is also supported. so the same config in .yml format would be

1
2
3
4
5
6
spring:
datasource:
url: jdbc:mysql://stage-server:3306/persondb
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver

You can get System Property value with the following system. In case when the system property is not defined, default value will be used.

1
app.tmp=${java.io.tmpdir:/mytmp}

You can also reference an environment variable like the system properties.

1
app.secret=${MY_SECRET:defaultsecret}

Common application properties

Various properties can be specified inside your application.properties file, inside your application.yml file, or as command line switches.

Spring boot defines common application properties in Appendix A. Common application properties. We can also create our own properties for our application.

Use Random Values

You can provide random values in the config files.

1
2
3
4
5
myRand:
randStr: ${random.value}
randInt: ${random.int}
randLong: ${random.long}
randUuid: ${random.uuid}

Reference a Value

You can reference another property in a config file.

1
2
3
4
app:
name: my-spring-boot-app
author: xing
intro: This is ${app.name} created by ${app.author}

@Value Annotation

You can inject some default value as string using @Value annotation

1
2
@Value("Some Default  String Value")
private String someValue;

Value from application.properties file

You can also get property value from a application.properties file.

1
2
3
4
5
6
7
8
9
10
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyServiceConfig {
@Value("${myservice.url}")
private String url;

// ...
}

In this example, you get myservice.url property from the application.properties file.

You can also provide some default value for the property. Here when app.secret is not defined in application.proerties file, “mydefaultsecret” will be used as the value

1
2
@Value("${app.secret:mydefaultsecret}")
private String secret;

Value from System Property

You can also get System property with the same syntax

1
2
@Value("${java.io.tmpdir}")
private String tmpDir;

You can also use SpEL to get system property too

1
2
@Value("#{systemProperties['java.io.tmpdir']}")
private String tmpdir;

Value from Environment Variable

You can also get environment variables such as HOME, PATH

1
2
@Value("${HOME}")
private String homeDir;

Bind Configuration to Java Object

use @ConfigurationProperties annotaiton to bind configuration to Java Object

1
2
3
4
5
6
7
8
@Component
@ConfigurationProperties(prefix = "myservice", ignoreUnknownFields = true)
public class ServiceConfig {
private String url;
private String username;
private String password;

}

You can also use @ConfigurationProperties annotation with @Bean annotation to bind configuration to a bean in a Config class file.

1
2
3
4
5
6
7
8
@Configuration
public class MyServiceConfig {
@Bean
@ConfigurationProperties(prefix = "myservice", ignoreUnknownFields = true)
public MyService myService() {
return new MyService();
}
}

For more information on @ConfigurationProperties annotation, see Guide to @ConfigurationProperties in Spring Boot

Register a Properties file

@PropertySource is an annotation that provides a convenient and declarative mechanism for adding a PropertySource to Spring’s Environment. To be used in conjunction with @Configuration classes.

1
2
3
4
5
6
7
@Configuration
@PropertySource("classpath:customdbsource.yml")
public class CustomDBConfig {
@Value("spring.datasource.customsource.driver-class-name")
private String url;
...
}

Here @PropertySource is used with @Configuration annotation, you can also use it with @SpringBootApplication annotation. You can use @Value to inject properties from property source. Or you can use Environment bean to get the property value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Configuration
@PropertySource("classpath:customdbsource.yml")
public class CustomDBConfig {

@Autowired
private Environment env;

public String getServiceUrl() {
return env.getProperty("other-service.url");
}

@Bean(name="customDataSource")
@Qualifier("customDataSource")
public DataSource CustomDataSource() {
return DataSourceBuilder.create()
.driverClassName(env.getProperty("spring.datasource.customsource.driver-class-name"))
.url(env.getProperty("spring.datasource.customsource.jdbc-url"))
.username(env.getProperty("spring.datasource.customsource.username"))
.password(env.getProperty("spring.datasource.customsource.password")).build();
}
}

If you have multiple config files, you can use multiple @PropertySource annotation or use @PropertySources to group them together.

for more info on @PropertySource, see Spring @PropertySource example by Mkyong

Environment Bean

You can use @Value to get the property value. An alternative is to use Environment bean to get the value.

In Sprint Boot, first autowire Environment bean

1
2
@Autowired
private Environment env;

Then we can get property value like this

1
2
3
env.getProperty("JAVA_HOME")

env.getProperty("app.name")

Profile specific Properties file

Applications are usually deployed to different environments. We can use add configurations for different environments. Just define “application-{environment}.properties” in src/main/resources directory.

Profile-specific properties files will override the non-profile specific properties file.

application-dev.yml

1
2
3
4
5
6
spring:
datasource:
url: jdbc:mysql://dev-server:3306/mydb
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver

application-stage.yml

1
2
3
4
5
6
spring:
datasource:
url: jdbc:mysql://stage-server:3306/mydb
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver

You can set active profile in the command line using program argument. in this case, system property spring.profiles.active is set to dev

1
java -jar app.jar --spring.profiles.active=dev

Use environment variable to set active profile

1
SPRING_PROFILES_ACTIVE=local gradle clean bootRun

For maven project, you can use -D to define system property

1
mvn spring-boot:run -Dspring-boot.run.profiles=local

You can set default profile in application.yml file

1
2
3
spring:
profiles:
default: local

Reference

Source Code: SpringBootExamples - config