I have a Spring Boot application and in one of the classes, I try to reference a property from the application.properties file using @Value
. But, the property does not get resolved. I have looked at similar posts and tried following the suggestions, but that didn't help. The class is:
@Configuration @ComponentScan @EnableAutoConfiguration public class PrintProperty { @Value("${file.directory}") private String fileDirectory; public void print() { System.out.println(fileDirectory); } }
I have the property file.directory in application.properties
. I have other fields as well.
Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. Spring @Value annotation also supports SpEL. Let's look at some of the examples of using @Value annotation.
Another method to access values defined in Spring Boot is by autowiring the Environment object and calling the getProperty() method to access the value of a property file.
Properties files are used to keep 'N' number of properties in a single file to run the application in a different environment. In Spring Boot, properties are kept in the application. properties file under the classpath. Note that in the code shown above the Spring Boot application demoservice starts on the port 9090.
Accessing the YAML Properties To access the YAML properties, we'll create an object of the YAMLConfig class, and access the properties using that object. In the properties file, we'll set the spring. profiles. active environment variable to prod.
I had the same problem like you. Here's my error code.
@Component public class GetExprsAndEnvId { @Value("hello") private String Mysecret; public GetExprsAndEnvId() { System.out.println("construct"); } public void print(){ System.out.println(this.Mysecret); } public String getMysecret() { return Mysecret; } public void setMysecret(String mysecret) { Mysecret = mysecret; } }
This is no problem like this, but we need to use it like this:
@Autowired private GetExprsAndEnvId getExprsAndEnvId;
not like this:
getExprsAndEnvId = new GetExprsAndEnvId();
Here, the field annotated with @Value is null because Spring doesn't know about the copy of GetExprsAndEnvId that is created with new and didn't know to how to inject values in it.
Make sure your application.properties file is under src/main/resources/application.properties. Is one way to go. Then add @PostConstruct as follows
Sample Application.properties
file.directory = somePlaceOverHere
Sample Java Class
@ComponentScan public class PrintProperty { @Value("${file.directory}") private String fileDirectory; @PostConstruct public void print() { System.out.println(fileDirectory); } }
Code above will print out "somePlaceOverhere"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With