Created
February 7, 2018 17:38
-
-
Save rahogata/0a5a648869329ffa5788140b811dd243 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 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.context.annotation.ComponentScan; | |
import org.springframework.core.env.Environment; | |
import org.springframework.stereotype.Component; | |
import org.springframework.stereotype.Service; | |
/** | |
* Boot Application. | |
*/ | |
@SpringBootApplication | |
@ComponentScan | |
public class DemoWebBootApp { | |
public static void main(String[] args) { | |
ApplicationContext ctx = SpringApplication.run(DemoWebBootApp.class, args); | |
DemoService demoService = ctx.getBean(DemoService.class); | |
demoService.dispayAppName(); | |
} | |
} | |
/** This class is for accessing properties of spring configuration files | |
* without injecting any Environment/@ConfigurationProperties classes. | |
* Advantages: | |
* 1. Can be used without any kind of dependecy injected in to services accessing properties. | |
* 2. Avoids creation new @ConfigurationProperties annotated classes for | |
* each prefix in configuration files. | |
* 3. Accessing properties in static way shortens code. | |
* 4. Can hold constants having property names which could be used to obtain values with | |
* Spring provided property sources like Environment or Java System properties. | |
* | |
* Disadvantages: | |
* 1. Properties can not be accessed by bean configuration files during context initialization. | |
* 2. During Spring context creation properties can be access if it is defined as a bean. | |
*/ | |
@Component | |
class ConfigDepository { | |
public static String APPNAME = "app.name"; | |
/** | |
* Set all properties. | |
*/ | |
@Autowired | |
public ConfigDepository(Environment env) { | |
APPNAME = env.getProperty(APPNAME); | |
} | |
} | |
/** | |
* | |
*/ | |
@Service | |
class DemoService { | |
public void dispayAppName() { | |
System.out.println(ConfigDepository.APPNAME); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment