I have a Spring MVC Controller class that needs a property set from a config.properties file. I was thinking that since I already use this config file to set some db properties, I could access it in a similar way to set this property. The difference is that my Controller class is annotated and not declared in an XML file, so I can't set the property that usual way. I have my config.properties ready to be used in my XML file as so:
<context:property-placeholder location="/WEB-INF/config.properties" />
I would like to set the following property in my controller class from an entry in this properties file:
@Controller
public class SampleUploadController {
private String audioFilePath;
public String getAudioFilePath() {
return audioFilePath;
}
// I want this set from the properties file I've declared in my
// XML file: e.g. ${props.audioFilePath}
public void setAudioFilePath(String audioFilePath) {
this.audioFilePath = audioFilePath;
}
}
Is this possible. If not, can somebody suggest how to get the property I need from the configuration file? It is located in my root WEB-INF. T开发者_开发问答he problem is that I do not have access to ServletContext at this point to get a reference to where this file is.
In Spring 3, you can use the @Value
annotation to do this, e.g.
@Value("${props.audioFilePath}")
public void setAudioFilePath(String audioFilePath) {
this.audioFilePath = audioFilePath;
}
Skaffman is correct, but be aware that properties loaded for use via only work in their own context. E.g., if you have an application context parent module which loads the properties, you cannot use @Value in beans allocated in the servlet context with those properties... they're just not visible.
精彩评论