Issue
I'm writing a Spring Boot application and am trying to load some values from a properties file using the @Value
annotation. However, the variables with this annotation remain null even though I believe they should get a value.
The files are located in src/main/resources/custom.propertes
and src/main/java/MyClass.java
.
(I have removed parts of the code that I believe are irrelevant from the snippets below)
MyClass.java
@Component
@PropertySource("classpath:custom.properties")
public class MyClass {
@Value("${my.property:default}")
private String myProperty;
public MyClass() {
System.out.println(myProperty); // throws NullPointerException
}
}
custom.properties
my.property=hello, world!
What should I do to ensure I can read the values from my property file?
Thanks!
Solution
@value
will be invoked after the object is created. Since you are using the property inside the constructor hence it is not available.
You should be using constructor injection anyway. It makes testing your class easier.
public MyClass(@Value("${my.property:default}") String myProperty) {
System.out.println(myProperty); // doesn't throw NullPointerException
}
Answered By - dassum