【发布时间】:2015-04-27 14:50:47
【问题描述】:
我正在尝试升级我们一些旧应用程序的库,其中一部分是从 Spring 3 迁移到 Spring 4.1.6。我有一个我认为是非常典型的配置,它使用 Maven 来引入依赖项,然后使用 Maven 配置文件和过滤来选择正确的属性文件来运行应用程序。看起来像这样。
pom.xml
<profiles>
<profile>
<id>dev</id>
<properties>
<app.env>Development</app.env>
</properties>
<build>
<resources>
<resource>
<directory>${basedir}/src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<webResources>
<webResource>
<directory>${basedir}/src/main/webapp/WEB-INF</directory>
<includes>
<include>web.xml</include>
</includes>
<filtering>true</filtering>
<targetPath>WEB-INF</targetPath>
</webResource>
</webResources>
</configuration>
</plugin>
</plugins>
</build>
</profile>
我的 spring 应用程序上下文位于带有 PropertySourcesPlaceholderConfigurer bean 定义的过滤资源目录中。 ${app.env} 被过滤掉以由 Development.properties 文件加载
ApplicaitonContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:com/tms/edu/settings/${app.env}.properties</value>
</list>
</property>
</bean>
此时我的理解是,当使用 ProperySourcesPlaceholderConfigurer 而不是旧的 PropertyPlaceHolderConfigurer 时,它应该自动将资源注册为 PropertySource,以便自动连接的 Environment 对象可以简单地调用 getProperty("db.location") 并拥有它在运行时可用。所以我应该能够在我扫描的包中有一个简单的类,它基本上可以做到这一点:
@Service
public class PropertyReader {
@Autowired
private Environment env;
public String getPropertyValue(String key) {
return env.getProperty(urlkey);
}
}
但这不起作用。 getProperty() 为应该工作的键返回 null 并在调试器中检查环境对象我没有看到我的资源加载到 propertySources 列表中。
我只是在寻找如何使用注释配置 PropertySource 的示例,但这不适用于我们在 Maven 构建中管理配置文件和属性的方式。我知道我可以使用 @Value ${} 样式的注释来获取这些值,并且效果很好。但是我仍然很好奇为什么 Environment 没有像我预期的那样工作。
【问题讨论】:
-
同样的问题,我什么都试过了。你解决问题了吗?
-
已经有一段时间了,所以这可能并不令人满意,但是通过代码看起来我可以在一个项目中使用它,但配置似乎与我在我的问题。我使用@Configuration @PropertySource("classpath:application.properties") 的其他项目只是硬编码在一个属性文件中。
标签: java spring maven spring-mvc