Issue
So, I have a simple properties file with the following entries:
my.value=123
another.value=hello world
This properties file is being loaded using a PropertyPlaceHolderConfigurer
, which references the properties file above.
I have the following class, for which I'm trying to load these properties in to like so:
public class Config
{
@Value("${my.value}")
private String mValue;
@Value("${another.value}")
private String mAnotherValue;
// More below...
}
The problem is that, mValue
and mAnotherValue
are ALWAYS null... yet in my Controllers, the value is being loaded just fine. What gives?
Solution
If instances of Config
are being instantiated manually via new
, then Spring isn't getting involved, and so the annotations will be ignored.
If you can't change your code to make Spring instantiate the bean (maybe using a prototype
-scoped bean), then the other option is to use Spring's load-time classloader weaving functionality (see docs). This is some low-level AOP which allows you to instantiate objects as you normally would, but Spring will pass them through the application context to get them wired up, configured, initialized, etc.
It doesn't work on all platforms, though, so read the above documentation link to see if it'll work for you.
Answered By - skaffman
Answer Checked By - Timothy Miller (JavaFixing Admin)