有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是否使用SpringXML实体在带注释的文件中设置属性?

我有一个Spring MVC控制器类,它需要一个来自配置的属性集。属性文件。我在想,既然我已经使用这个配置文件来设置一些db属性,我可以用类似的方式访问它来设置这个属性。不同之处在于,我的控制器类是带注释的,而不是在XML文件中声明的,所以我不能以通常的方式设置属性。我有我的配置。准备在我的XML文件中使用的属性如下:

    <context:property-placeholder location="/WEB-INF/config.properties" />

我想在此属性文件中的条目中设置控制器类中的以下属性:

@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;
    } 
}

这可能吗。如果没有,有人能建议如何从配置文件中获取我需要的属性吗?它位于我的根WEB-INF中。问题是,我现在没有访问ServletContext的权限来获取该文件所在位置的引用


共 (2) 个答案

  1. # 1 楼答案

    在Spring 3中,可以使用^{}注释来实现这一点,例如

    @Value("${props.audioFilePath}")
    public void setAudioFilePath(String audioFilePath) {
        this.audioFilePath = audioFilePath;
    } 
    
  2. # 2 楼答案

    Skaffman是正确的,但请注意,为使用而加载的属性只能在它们自己的上下文中工作。例如,如果您有一个加载属性的应用程序上下文父模块,则不能在servlet上下文中分配的bean中使用@Value和这些属性。。。它们就是看不见