1+ package com .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:configprops.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+ }
0 commit comments