Reputation: 81
I have a properties file under /src/main/resources/ and I want to load data from it using Spring.
In my Spring-context.xml I have this :
<context:property-placeholder location="classpath:UserUtil.properties" />
and also have <context:component-scan base-package="com.myApp" />
and in my class I load it like :
@Value("${injectMeThis}")
private String injectMeThis;
but the value is always null
EDIT:
to check if the value, I use this :
System.out.println(new myClass().getInjectMeThis());
Upvotes: 2
Views: 15468
Reputation: 124526
System.out.println(new myClass().getInjectMeThis());
Spring will only parse @Value
annotations on beans it knows. The code you use creates an instance of the class outside the scope of Spring and as such Spring will do nothing with it.
Assuming you have setup your application context correctly a @Value
cannot be null
as that will stop the correct startup of your application.
Your XML file contains a <context:component-scan />
assuming myClass
is part of that package the easiest solution is to add @Component
to myClass
and then retrieve the instance from the context instead of creating a new instance.
Upvotes: 6
Reputation: 588
In your class, add class level annotation @PropertySource("UserUtil.properties")
. This should solve the problem.
Upvotes: -1