Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将servlet contextPath与PropertySource一起使用?_Java_Spring_Spring Mvc - Fatal编程技术网

Java 如何将servlet contextPath与PropertySource一起使用?

Java 如何将servlet contextPath与PropertySource一起使用?,java,spring,spring-mvc,Java,Spring,Spring Mvc,我想加载一个与contextPath同名的配置文件。以下是我尝试的代码: @配置 @PropertySource(“文件:${user.home}/#{servletContext.contextPath}.properties”) 公共类属性配置{ @豆子 公共静态属性资源占位符配置器属性PlaceHolderConfigure() { 返回新属性资源占位符配置器(); } } 上述代码不起作用,因为未解析#{servletContext.contextPath} 有没有一个简单的方法可以做

我想加载一个与contextPath同名的配置文件。以下是我尝试的代码:

@配置
@PropertySource(“文件:${user.home}/#{servletContext.contextPath}.properties”)
公共类属性配置{
@豆子
公共静态属性资源占位符配置器属性PlaceHolderConfigure()
{
返回新属性资源占位符配置器();
}
}
上述代码不起作用,因为未解析
#{servletContext.contextPath}

有没有一个简单的方法可以做到这一点

@EnableWebMvc
@Configuration
@PropertySource("classpath:/my.properties")
public class MyConfig {
 public @Value("#{ servletContext.getContextPath() }") String test;
 }
  • 试试这个

似乎在
@PropertySource
中无法访问
servletContext
。解决方法是使用
@Value
获取contextPath值

@配置
公共类属性配置{
@豆子
公共静态属性PlaceHolderConfigurer属性PlaceHolderConfigurer(
@值(“#{servletContext.contextPath}”)字符串contextPath)引发错误的格式异常
{
final PropertyPlaceholderConfigurer=new PropertyPlaceholderConfigurer();
setLocation(新的UrlResource(“文件:“+System.getProperty(“user.home”)+”/“+contextPath+”.properties”));
返回配置器;
}
}

谢谢,我确实可以用
@value
检索值。奇怪的是,它不能直接在
@PropertySource