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:
  1. @Autowired
  2. private Environment env;
2) User getProperty(String key) method to get a value for a specific property. Like this:
  1. String keyValue = env.getProperty(key);
Let’s assume I have these properties in my application.properties file:
  1. app.title=Learning Spring Boot
  2. 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.

  1. String title = env.
    getProperty("app.title");

  1. 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:
  1. @Value("${app.title}")
  2. private String appTitle;

Reading Application Properties with @ConfigurationProperties

For example, let’s assume we have the same application.properties file:
  1. app.title=Learning Spring Boot
  2. 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:
  1. @ConfigurationProperties("app")
Here is an example of Java class annotated with @ConfigurationProperties annotation:

  1. import org.springframework.boot.context.properties.ConfigurationProperties;
  2. import org.springframework.stereotype.Component;
  3. @Component
  4. @ConfigurationProperties("app")
  5. public class AppProperties {
  6. private String title;
  7. private String description;

  8. //getters and setters
  9. }
To use this class in Rest Controller or Service class we simply autowire it by using the @Autowired annotation.
  1. @RestController
  2. @RequestMapping("app")
  3. public class AppController {
  4. @Autowired
  5. AppProperties myAppProperties;
  6. //to get title
  7. myAppProperties.getTitle();
  8. //to get description
  9. myAppProperties.getTitle();
  10. }

Comments

Popular posts from this blog

gsutil Vs Storage Transfer Service Vs Transfer Appliance

SQL basic interview question