【发布时间】:2016-08-12 10:34:27
【问题描述】:
我在src/main/resources 中有一个属性文件。
Spring 4.0 和 Java 1.8 项目。
mock.properties
key=test
WEB-INF/web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
WEB-INF/mvc-dispatcher-servlet.xml
<context:component-scan base-package="com.x.y.z.*">
</context:component-scan>
<context:annotation-config />
<context:spring-configured />
<context:property-placeholder location="classpath:mock.properties"
order="-1" ignore-resource-not-found="true" ignore-unresolvable="true" />
<mvc:annotation-driven />
Controller.java ...我可以访问控制器中属性键的值。
@Controller
@RequestMapping("/xyz")
public class EC2Controller {
@Value("${key}")
String v;
}
Helper.java ...无法访问任何属性。总是得到“null”
@Component
public class Helper {
@Value("${key}")
String v;
}
我还尝试了论坛和 spring 文档中建议的各种选项,但助手无法阅读道具。我也尝试了以下操作
@Configuration
@PropertySource("classpath:mock.properties")
public class Helper {
@Value("${key}")
String v;
@Bean
public static PropertySourcesPlaceholderConfigurer
propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
和
@Configuration
@PropertySource("classpath:mock.properties")
public class Helper {
@Autowired
Environment env;
String v = env.getProperty("key");
}
没有任何作用。
【问题讨论】:
-
澄清一下:您的@Autowire 注释实际上是@Autowired(带有一个d),对吗?
-
我有一个示例工作代码@github.com/shaimakh/so36732090
-
嗨@Sanj..是的,我知道它在理想情况下应该如何工作。但我无法弄清楚我的应用程序出了什么问题。
-
有趣。似乎您拥有所需的所有组件。呃,让我想起了我挣扎了很长时间以及试图让它发挥作用的糟糕回忆。
-
@WillMcavoy - 我从你的帖子中获取了所有信息,它正在工作。您可以在 github 上发布示例吗?
标签: java spring spring-mvc properties-file