read this article on SO, and had some clarifying questions.
I put my config.properties under src/main/resources
In spring-servlet.xml config file
I added the following:
<context:property-placeholder location="classpath:config.properties"/>
In my business layer, I am trying to access it via
@Value("${upload.file.path}")
private String uploadFilePath;
Eclipse shows error:
The attribute value is undefined for the annotation type Value
Can i not access the property in the business layer or are property files only read in the controller?
UPDATE::
src/main/java/com.companyname.controllers/homecontroller.java
public String home(Locale locale, Model model) {
MyServiceObject myObj = new MyServiceObject();
System.out.println("Property from my service object: = " + myObj.PropertyValue());
if(myObj.PerformService())
{
///
}
}
src/main/java/com.companyname.services/MyService.java
public class MyServiceObject {
@Value("${db.server.ip}")
private String _dbServerIP;
public String PropertyValue() {
return _dbServerIPaseURL;
}
}
Please check that you import Value from org.springframework.beans.factory.annotation package:
also the property placeholder must be declared in the respective context configuration file, in case of controller it’s likely Spring dispatcher servlet configuration file.
update You are confusing
property-placeholderthat post processes bean values, that contain dollar symbol${<property name>}with Spring expression language container extension that process values containing a hash symbol#{<Spring expression language expression>}, in the link you have shown the latter approach is used.regarding the instantiation of MyServiceObject myObj
If you want the object to be managed by Spring you should delegate its creation to the container:
if
MyServiceObjectis a stateless service then it’s a singleton with the singleton bean scope, you should register it in your application context, for example with the following xml configuration:and inject it to your controller:
if many instances of
MyServiceObjectare required, you can declare it as a bean with some other (non-singleton) bean scope (prototype, or request, for example).However, as there’s only one instance of the controller, you can’t merely let the Spring container to autowire
MyServiceObjectinstance to the controller field, because there will be only one field and many instances ofMyServiceObjectclass. You can read about the different approaches(for the different bean scopes) for resolving this issue in the respective section of the documentation.