Skip to content

Commit 9ab810a

Browse files
committed
loading json props
1 parent 2501cc9 commit 9ab810a

8 files changed

Lines changed: 306 additions & 3 deletions

File tree

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
package org.baeldung.properties;
22

3-
import org.springframework.boot.SpringApplication;
43
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
4+
import org.springframework.boot.builder.SpringApplicationBuilder;
55
import org.springframework.context.annotation.ComponentScan;
66

77
@EnableAutoConfiguration
8-
@ComponentScan(basePackageClasses = ConfigProperties.class)
8+
@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class })
99
public class ConfigPropertiesDemoApplication {
1010
public static void main(String[] args) {
11-
SpringApplication.run(ConfigPropertiesDemoApplication.class);
11+
new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer())
12+
.run();
1213
}
14+
1315
}
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package org.baeldung.properties;
2+
3+
import org.springframework.boot.context.properties.ConfigurationProperties;
4+
import org.springframework.context.annotation.Configuration;
5+
6+
@Configuration
7+
@ConfigurationProperties(prefix = "custom")
8+
public class CustomJsonProperties {
9+
10+
private String host;
11+
12+
private int port;
13+
14+
private boolean resend;
15+
16+
private Person sender;
17+
18+
public static class Person {
19+
20+
private String name;
21+
private String address;
22+
23+
public String getName() {
24+
return name;
25+
}
26+
27+
public void setName(String name) {
28+
this.name = name;
29+
}
30+
31+
public String getAddress() {
32+
return address;
33+
}
34+
35+
public void setAddress(String address) {
36+
this.address = address;
37+
}
38+
}
39+
40+
public String getHost() {
41+
return host;
42+
}
43+
44+
public void setHost(String host) {
45+
this.host = host;
46+
}
47+
48+
public int getPort() {
49+
return port;
50+
}
51+
52+
public void setPort(int port) {
53+
this.port = port;
54+
}
55+
56+
public boolean isResend() {
57+
return resend;
58+
}
59+
60+
public void setResend(boolean resend) {
61+
this.resend = resend;
62+
}
63+
64+
public Person getSender() {
65+
return sender;
66+
}
67+
68+
public void setSender(Person sender) {
69+
this.sender = sender;
70+
}
71+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package org.baeldung.properties;
2+
3+
import java.util.LinkedHashMap;
4+
import java.util.List;
5+
6+
import org.springframework.boot.context.properties.ConfigurationProperties;
7+
import org.springframework.context.annotation.Configuration;
8+
import org.springframework.context.annotation.PropertySource;
9+
10+
@Configuration
11+
@PropertySource(value = "classpath:configprops.json", factory = JsonPropertySourceFactory.class)
12+
@ConfigurationProperties
13+
public class JsonProperties {
14+
15+
private String host;
16+
17+
private int port;
18+
19+
private boolean resend;
20+
21+
private List<String> topics;
22+
23+
private LinkedHashMap<String, ?> sender;
24+
25+
public LinkedHashMap<String, ?> getSender() {
26+
return sender;
27+
}
28+
29+
public void setSender(LinkedHashMap<String, ?> sender) {
30+
this.sender = sender;
31+
}
32+
33+
public List<String> getTopics() {
34+
return topics;
35+
}
36+
37+
public void setTopics(List<String> topics) {
38+
this.topics = topics;
39+
}
40+
41+
public int getPort() {
42+
return port;
43+
}
44+
45+
public void setPort(int port) {
46+
this.port = port;
47+
}
48+
49+
public boolean isResend() {
50+
return resend;
51+
}
52+
53+
public void setResend(boolean resend) {
54+
this.resend = resend;
55+
}
56+
57+
public String getHost() {
58+
return host;
59+
}
60+
61+
public void setHost(String host) {
62+
this.host = host;
63+
}
64+
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package org.baeldung.properties;
2+
3+
import java.io.IOException;
4+
import java.util.Collection;
5+
import java.util.Collections;
6+
import java.util.LinkedHashMap;
7+
import java.util.List;
8+
import java.util.Map;
9+
import java.util.Optional;
10+
import java.util.Set;
11+
import java.util.stream.Collectors;
12+
13+
import org.springframework.context.ApplicationContextInitializer;
14+
import org.springframework.context.ConfigurableApplicationContext;
15+
import org.springframework.core.env.MapPropertySource;
16+
import org.springframework.core.env.PropertySource;
17+
import org.springframework.core.io.Resource;
18+
19+
import com.fasterxml.jackson.databind.ObjectMapper;
20+
21+
public class JsonPropertyContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
22+
23+
private final static String CUSTOM_PREFIX = "custom.";
24+
25+
@Override
26+
@SuppressWarnings("unchecked")
27+
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
28+
try {
29+
Resource resource = configurableApplicationContext.getResource("classpath:configpropscustom.json");
30+
Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class);
31+
Set<Map.Entry> set = readValue.entrySet();
32+
List<MapPropertySource> propertySources = convertEntrySet(set, Optional.empty());
33+
for (PropertySource propertySource : propertySources) {
34+
configurableApplicationContext.getEnvironment()
35+
.getPropertySources()
36+
.addFirst(propertySource);
37+
}
38+
} catch (IOException e) {
39+
throw new RuntimeException(e);
40+
}
41+
}
42+
43+
private static List<MapPropertySource> convertEntrySet(Set<Map.Entry> entrySet, Optional<String> parentKey) {
44+
return entrySet.stream()
45+
.map((Map.Entry e) -> convertToPropertySourceList(e, parentKey))
46+
.flatMap(Collection::stream)
47+
.collect(Collectors.toList());
48+
}
49+
50+
private static List<MapPropertySource> convertToPropertySourceList(Map.Entry e, Optional<String> parentKey) {
51+
String key = parentKey.map(s -> s + ".")
52+
.orElse("") + (String) e.getKey();
53+
Object value = e.getValue();
54+
return covertToPropertySourceList(key, value);
55+
}
56+
57+
@SuppressWarnings("unchecked")
58+
private static List<MapPropertySource> covertToPropertySourceList(String key, Object value) {
59+
if (value instanceof LinkedHashMap) {
60+
LinkedHashMap map = (LinkedHashMap) value;
61+
Set<Map.Entry> entrySet = map.entrySet();
62+
return convertEntrySet(entrySet, Optional.ofNullable(key));
63+
}
64+
String finalKey = CUSTOM_PREFIX + key;
65+
return Collections.singletonList(new MapPropertySource(finalKey, Collections.singletonMap(finalKey, value)));
66+
}
67+
68+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package org.baeldung.properties;
2+
3+
import java.io.IOException;
4+
import java.util.Map;
5+
6+
import org.springframework.core.env.MapPropertySource;
7+
import org.springframework.core.io.support.EncodedResource;
8+
import org.springframework.core.io.support.PropertySourceFactory;
9+
10+
import com.fasterxml.jackson.databind.ObjectMapper;
11+
12+
public class JsonPropertySourceFactory implements PropertySourceFactory {
13+
14+
@Override
15+
public org.springframework.core.env.PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
16+
Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class);
17+
return new MapPropertySource("json-property", readValue);
18+
}
19+
20+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"host" : "mailer@mail.com",
3+
"port" : 9090,
4+
"resend" : true,
5+
"topics" : ["spring", "boot"],
6+
"sender" : {
7+
"name": "sender",
8+
"address": "street"
9+
}
10+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"host" : "mailer.custom@mail.com",
3+
"port" : 8081,
4+
"resend" : true,
5+
"sender" : {
6+
"name": "sender.custom",
7+
"address": "street.custom"
8+
}
9+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package org.baeldung.properties;
2+
3+
import java.util.Arrays;
4+
5+
import org.hamcrest.Matchers;
6+
import org.junit.Assert;
7+
import org.junit.Test;
8+
import org.junit.runner.RunWith;
9+
import org.springframework.beans.factory.annotation.Autowired;
10+
import org.springframework.test.context.ContextConfiguration;
11+
import org.springframework.test.context.junit4.SpringRunner;
12+
13+
@RunWith(SpringRunner.class)
14+
@ContextConfiguration(classes = ConfigPropertiesDemoApplication.class, initializers = JsonPropertyContextInitializer.class)
15+
public class JsonPropertiesIntegrationTest {
16+
17+
@Autowired
18+
private JsonProperties jsonProperties;
19+
20+
@Autowired
21+
private CustomJsonProperties customJsonProperties;
22+
23+
@Test
24+
public void givenJsonPropertySource_whenPropertySourceFactoryUsed_thenLoadFlatValues() {
25+
Assert.assertEquals("mailer@mail.com", jsonProperties.getHost());
26+
Assert.assertEquals(9090, jsonProperties.getPort());
27+
Assert.assertTrue(jsonProperties.isResend());
28+
}
29+
30+
@Test
31+
public void givenJsonPropertySource_whenPropertySourceFactoryUsed_thenLoadListValues() {
32+
Assert.assertThat(jsonProperties.getTopics(), Matchers.is(Arrays.asList("spring", "boot")));
33+
}
34+
35+
@Test
36+
public void givenJsonPropertySource_whenPropertySourceFactoryUsed_thenNestedValuesLoadedAsMap() {
37+
Assert.assertEquals("sender", jsonProperties.getSender()
38+
.get("name"));
39+
Assert.assertEquals("street", jsonProperties.getSender()
40+
.get("address"));
41+
}
42+
43+
@Test
44+
public void givenCustomJsonPropertySource_whenLoadedIntoEnvironment_thenFlatValuesPopulated() {
45+
Assert.assertEquals("mailer.custom@mail.com", customJsonProperties.getHost());
46+
Assert.assertEquals(8081, customJsonProperties.getPort());
47+
Assert.assertTrue(customJsonProperties.isResend());
48+
}
49+
50+
@Test
51+
public void givenCustomJsonPropertySource_whenLoadedIntoEnvironment_thenValuesLoadedIntoClassObject() {
52+
Assert.assertNotNull(customJsonProperties.getSender());
53+
Assert.assertEquals("sender.custom", customJsonProperties.getSender()
54+
.getName());
55+
Assert.assertEquals("street.custom", customJsonProperties.getSender()
56+
.getAddress());
57+
}
58+
59+
}

0 commit comments

Comments
 (0)