Reading application.properties in Spring Boot

-

Environment object

@Value

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@SpringBootTest
public class AppPropertiesTests {

@Autowired
private Environment env;

@Value("${test.hello}")
private String hello;

@Test
public void test() {
System.out.println(env.getProperty("spring.profiles.active"));
System.out.println(hello);
}
}

@ConfigurationProperties

application-local.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
test:
hello: hello

app:
url: www.test.com
mail:
#Simple properties
hostname: mailer@mail.com
port: 9000
from: mailer@mail.com

#List properties
defaultRecipients:
- admin@mail.com
- owner@mail.com
#Map Properties
additionalHeaders:
redelivery: true
secure: true
#Object properties
credentials:
username: john
password: password
authMethod: SHA1

Mail.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.example.demo.model;

import java.util.List;
import java.util.Map;

import lombok.Data;

@Data
public class Mail {

private String host;
private int port;
private String from;
private List<String> defaultRecipients;
private Map<String, String> additionalHeaders;
private Credentials credentials;

}

AppProperties.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.example.demo.config;

import com.example.demo.model.Mail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import lombok.Data;

/**
* ConfigProperties
*/
@Data
@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {

@Autowired
private Environment env;

private String url;
private Mail mail;

public String get(String key) {

return env.getProperty(key);
}
}

AppPropertiesTest.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.example.demo.config;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;

import com.example.demo.config.AppProperties;

import static org.assertj.core.api.Assertions.assertThat;

/**
* ConfigPropertiesTests
*/
@SpringBootTest
public class AppPropertiesTest {

@Autowired
private AppProperties appProperties;

@Autowired
private Environment env;

@Value("${test.hello}")
private String hello;

@Test
public void test() {

assertThat(env.getProperty("spring.profiles.active")).asString().isEqualTo("local");
assertThat(appProperties.getUrl()).isEqualTo("www.test.com");
assertThat(appProperties.getMail().getHost()).isEqualTo("mailer@mail.com");

}
}

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×