Reading application.properties in Spring Boot
Read application.properties Using the Environment
1) Use the @Autowired annotation to inject the Environment object into your Rest Controller or Service class, like so:
- @Autowired
- private Environment env;
2) User getProperty(String key) method to get a value for a specific property. Like this:
- String keyValue = env.getProperty(key);
Let’s assume I have these properties in my application.properties file:
- app.title=Learning Spring Boot
- app.description=Working with properties file
and I need to create a Web Service endpoint that accepts property key name as request parameter and returns property value.
String title = env.getProperty("app.title");
String description = env.getProperty("app.description");
Reading Properties with @Value Annotation
To read the value of app.title property, annotate the class field with @Value annotation like so:
- @Value("${app.title}")
- private String appTitle;
Reading Application Properties with @ConfigurationProperties
For example, let’s assume we have the same application.properties file:
- app.title=Learning Spring Boot
- app.description=Working with properties file
Because each of the property names starts with a prefix of app we will need to annotation our Java Bean with:
- @ConfigurationProperties("app")
Here is an example of Java class annotated with @ConfigurationProperties annotation:
- import org.springframework.boot.context.properties.ConfigurationProperties;
- import org.springframework.stereotype.Component;
- @Component
- @ConfigurationProperties("app")
- public class AppProperties {
- private String title;
- private String description;
- //getters and setters
- }
To use this class in Rest Controller or Service class we simply autowire it by using the @Autowired annotation.
- @RestController
- @RequestMapping("app")
- public class AppController {
- @Autowired
- AppProperties myAppProperties;
- //to get title
- myAppProperties.getTitle();
- //to get description
- myAppProperties.getTitle();
- }
Comments
Post a Comment