How to access application properties in spring boot application?
In spring boot applications it is a good practice to keep all the configuration inside application.properties file. We can have multiple application.properties files based on the environments. Following is an example of environment based application.properties file:
-rw-r--r-- 1 joe staff 922 Dec 4 14:26 application-prod.properties -rw-r--r-- 1 joe staff 930 Dec 4 14:26 application-stage.properties -rw-r--r-- 1 joe staff 879 Dec 4 14:26 application-test.properties -rw-r--r-- 1 joe staff 8439 Dec 4 14:26 application.properties
Many developers keep the settings or config inside java code in spring boot. Keeping settings or config inside java code is not a good practice.
Using @value annotation
We can use the @Value annotation and access the property like below:
@Value("${arc.target.environment}") private String targetEnvironment;
Using @Autowired to Environment
We can use spring provided @Autowired to inject Environment to the bean.
@Autowired private Environment environments; public void getApplicationProperties() { String path = environments.getProperty("arc.target.mode"); }
Using @ConfigurationProperties to Environment
@ConfigurationProperties can be used like below to get the application properties.
arc.environments.stage.endpoint.image=api-url-image
@Configuration @ConfigurationProperties(prefix = "arc") @Getter @Setter public class ArcEndpointConfig { private Mapenvironments = new HashMap<>(); @Getter @Setter public static class Endpoint{ private Map endpoint = new HashMap<>(); } }