Spring 版本 4.2.2
:以下内容的 Java Config 替代品是什么:
<bean id="placeholderConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/conf/mars.properties" />
</bean>
我在其中一个配置中有以下内容。文件:
@Configuration
@EnableTransactionManagement
@ComponentScan
@PropertySource("file:WEB-INF/conf/mars.properties")
public class JpaConfig {
private static final String DB_DRIVER = "a";
private static final String DB_URL = "b";
private static final String DB_USERNAME = "c";
private static final String DB_PASSWORD = "d";
private static final String DB_PLATFORM = "e";
@Resource
private Environment env;
@Bean(destroyMethod="close")
public DataSource dataSource() {
org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
PoolProperties p = new PoolProperties();
p.setUrl(env.getProperty(DB_URL));
p.setDriverClassName(env.getProperty(DB_DRIVER));
p.setUsername(env.getProperty(DB_USERNAME));
p.setPassword(env.getProperty(DB_PASSWORD));
....
}
这会导致以下运行时错误:
Caused by: java.io.FileNotFoundException: \WEB-INF\conf\mars.properties (The system cannot find the path specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
我尝试了以下变体但无济于事:
@PropertySource("file://WEB-INF/conf/mars.properties")
这是一个基于 XML 配置的应用程序,我正在将其转换为 Java Config。
最佳答案
你只需要
@PropertySource("/WEB-INF/conf/mars.properties")
Spring 将使用 DefaultResourceLoader#getResource(String)
。对于以 /
开头的路径,这委托(delegate)给 getResourceByPath
,它被 AbstractRefreshableWebApplicationContext
覆盖(AnnotationConfigWebApplicationContext
的父类(super class)处理@Configuration
).
然后这将创建一个 ServletContextResource
可以成功定位相对于 servlet 上下文的资源。
关于java - Spring @PropertySource,如何读取不在类路径上,而是在WEB-INF下的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34667208/