我正在尝试弄清楚如何将属性文件的值获取到我的 Spring 环境属性中。
Spring 3.1 之前的方法是这样的:
<context:property-placeholder location="classpath:my.properties" />
<bean id="myBean" class="com.whatever.MyBean">
<property name="someValue" value="${myProps.value}" />
<!-- etc -->
</bean>
我也可以这样做:
public class MyBean {
@Value(value = "#{myProps.value}")
private String someValue;
}
现在我表面上可以从 Environment 类中提取属性,这似乎是一种比在 xml 或 bean 本身中使用笨重的 #{myProps.value} 语法更简洁的获取属性的方法。
我在 XML 中尝试过:
<bean
class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="location">
<value>classpath:my.properties</value>
</property>
</bean>
但是这些属性不会添加到环境中。
我知道我可以使用 PropertySource属性,但我没有使用注释进行配置。
那么我如何设置我的 bean/xml 以便我的 props 中的变量设置在环境中可用?此外,如何将这些值注入(inject)到我的 bean 中,而不必明确地说“environmentInstance.getProperty("myProps.value")?
最佳答案
对于网络应用程序
如果您希望在处理 XML bean 定义之前填充环境,则应实现 ApplicationContextInitializer(),如 the Spring Source blog 中所述。
<context-param>
<param-name>contextInitializerClasses</param-name>
<param-value>com.bank.MyInitializer</param-value>
</context-param>
这是博客中示例的稍加修改的版本
public class MyInitializer implements
ApplicationContextInitializer<ConfigurableWebApplicationContext> {
public void initialize(ConfigurableWebApplicationContext ctx) {
ResourcePropertySource ps;
try {
ps = new ResourcePropertySource(new ClassPathResource(
"my.properties"));
} catch (IOException e) {
throw new AssertionError("Resources for my.properties not found.");
}
ctx.getEnvironment().getPropertySources().addFirst(ps);
}
}
对于独立应用程序
基本上是一样的,可以修改AbstractApplicationContext
的环境直接
ResourcePropertySource ps;
try {
ps = new ResourcePropertySource(new ClassPathResource(
"my.properties"));
}catch (IOException e) {
throw new AssertionError("Resources for my.properties not found.");
}
//assuming that ctx is an AbstractApplicationContext
ctx.getEnvironment().getPropertySources().addFirst(ps);
附注该答案的早期版本显示了尝试从 bean 修改环境,但这似乎是在 SO 上传播的反模式,因为您肯定希望甚至在之前填充环境属性源列表XmlBeanDefinitionReader
开始处理 XML 以使占位符在 <import/>
内工作声明。
关于文件中的 Spring 环境属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14223788/