2

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());
Kilo Batata
  • 81
  • 1
  • 2
  • 6

2 Answers2

6
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.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
-1

In your class, add class level annotation @PropertySource("UserUtil.properties"). This should solve the problem.

ajith george
  • 538
  • 1
  • 5
  • 14
  • That annotation will only be usable on `@Configuration` classes not other classes. Also that annotation without a `PropertySourcesPlaceHolderConfigurer` or `` doesn't do anything. – M. Deinum Jun 14 '17 at 10:56
  • This will work for any components.Not just @Configuration class. – ajith george Jun 14 '17 at 10:58
  • Then how come it is working for a class with @Component annotation? – ajith george Jun 14 '17 at 11:05
  • It will work for `@Configuration` classes and lite configuration classes (basically it (kind of) works due to the conditions in the [`ConfigurationClassUtils`](https://github.com/spring-projects/spring-framework/blob/master/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassUtils.java#L80). So it depends on what your class is but it doesn't work for regular classes. (Next to that it also is a bit strange to have it not on a `@Configuration` class). But here it won't make a difference as that does (partially) the same as ``. – M. Deinum Jun 14 '17 at 11:09
  • It do for a @Component class too. May be it is strange for a component to have it but just want to know why it shouldn't work for a component. – ajith george Jun 14 '17 at 11:12
  • M.Deinum, can you please clarify on why @Component class should not use @PropertySource? and why it will not work if used together? – ajith george Jun 14 '17 at 12:29