Created
February 7, 2018 18:17
-
-
Save rahogata/1de6ee750dd109c57dfb7ceb61d2350a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
*/ | |
package com.rahogata.demowebapp; | |
import java.lang.reflect.Field; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.boot.SpringApplication; | |
import org.springframework.boot.autoconfigure.SpringBootApplication; | |
import org.springframework.context.ApplicationContext; | |
import org.springframework.core.env.Environment; | |
import org.springframework.stereotype.Component; | |
import org.springframework.stereotype.Service; | |
/** | |
* This code snippet is a proposal of managing application configurations | |
* at one place and accessing them easily. | |
* Feb 7, 2018 | |
*/ | |
@SpringBootApplication | |
public class ConfigReflectionPropApplication { | |
public static void main(String[] args) { | |
ApplicationContext ctx = SpringApplication.run(ConfigReflectionPropApplication.class, args); | |
SampleService sampleService = ctx.getBean(SampleService.class); | |
sampleService.displayAppDetails(); | |
} | |
} | |
/** | |
* Using reflections to set static fields during context initialization | |
* to eliminate initialization statements inside constructor. | |
*/ | |
@Component | |
class Config { | |
public static String APPNAME = "app.name"; | |
public static String APPVERSION = "app.version"; | |
/** | |
* @throws IllegalAccessException | |
* | |
*/ | |
@Autowired | |
public Config(Environment env) throws IllegalAccessException { | |
Field[] fields = this.getClass().getDeclaredFields(); | |
for (Field field : fields) { | |
String key = (String) field.get(null); | |
field.set(null, env.getProperty(key)); | |
} | |
} | |
} | |
/** | |
* Service using a configuration values. | |
*/ | |
@Service | |
class SampleService { | |
public void displayAppDetails() { | |
System.out.println("App name:" + Config.APPNAME + ", " + "version:" + Config.APPVERSION); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment