Reading values from application.properties file
Introduction:
Application properties may vary from other environments. like DEV, QA, UAT and PROD. using spring boot different environments can be configured and updated without affecting other environment files.
Accessing values within spring boot:
There are 2 ways to inject value.
- using value annotation
- using Environment object
Using value annotation:
It's a pre-defined annotation provided by spring framework. which is used to get value from the property file by providing property key name.
the annotation will import from the below package org.springframework.beans.factory.annotation.Value
knownLanguage=java
Test.java
public class Test {
@Value("${knownLanguage}")
private static String knownLanguage;
}
class should annotate with any spring provided stereotype annotations like @Component, @Controller, @RestController, @Configuration etc.. otherwise unable to fetch value using @value annotation
Using Environment Object:
Another method is to access value of property key by autowiring the Environment object. and calling the getProperty() method.
and getProperty() method accepts a single parameter which is string data type and that should be property key name. and it returns value of that property if it exists. if that key doesn't exists it will return null value.
private Environment env;
public void getValue() {
return env.getProperty("knownLanguage");
}
Environment is an interface. which is imported from org.springframework.core.env package.