1+ package com .stubbornjava .common ;
2+
3+ import java .util .List ;
4+
5+ import org .slf4j .Logger ;
6+ import org .slf4j .LoggerFactory ;
7+
8+ import com .google .common .base .Preconditions ;
9+ import com .google .common .collect .Lists ;
10+ import com .typesafe .config .Config ;
11+ import com .typesafe .config .ConfigFactory ;
12+ import com .typesafe .config .ConfigRenderOptions ;
13+
14+ //{{start:config}}
15+ public class Configs {
16+ private static final Logger logger = LoggerFactory .getLogger (Configs .class );
17+ /*
18+ * I am letting the typesafe configs bleed out on purpose here.
19+ * We could abstract out and delegate but its not worth it.
20+ * I am gambling on the fact that I will not switch out the config library.
21+ */
22+ private static final Config system = ConfigFactory .systemProperties ();
23+ private static final Config properties = new Builder ().envAwareApp ().build ();
24+
25+ public static Config system () {
26+ return system ;
27+ }
28+
29+ public static Config properties () {
30+ return properties ;
31+ }
32+
33+ public static class Builder {
34+ private final List <String > configs ;
35+
36+ public Builder () {
37+ this .configs = Lists .newLinkedList ();
38+ }
39+
40+ public Builder withResource (String resource ) {
41+ configs .add (resource );
42+ return this ;
43+ }
44+
45+ public Builder envAwareApp () {
46+ String env = system .hasPath ("env" ) ? system .getString ("env" ) : "local" ;
47+ String envFile = "application." + env + ".conf" ;
48+ configs .add (envFile );
49+ configs .add ("application.conf" );
50+ return this ;
51+ }
52+
53+ public Config build () {
54+ logger .info ("Loading configs first row is highest priority, second row is fallback and so on" );
55+ configs .forEach (logger ::info );
56+ Preconditions .checkArgument (configs .size () > 0 , "No config resources specified!" );
57+ Config appConfig = ConfigFactory .parseResources (configs .remove (0 ));
58+ for (String resource : configs ) {
59+ appConfig = appConfig .withFallback (ConfigFactory .parseResources (resource ));
60+ }
61+ logger .debug ("Logging properties. Make sure sensitive data such as passwords or secrets are not logged!" );
62+ logger .debug (appConfig .root ().render (ConfigRenderOptions .concise ().setFormatted (true )));
63+ return appConfig ;
64+ }
65+ }
66+
67+ public static void main (String [] args ) {
68+ Configs .properties ();
69+ }
70+ }
71+ //{{end:config}}
0 commit comments