Spring @PropertySource,如何读取不在classpath中,而是在WEB-INF下的文件

Spring @PropertySource, how to read a file not on the classpath, but under WEB-INF

Spring 版本 4.2.2:以下内容的 Java 配置替换是什么:

<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 配置。

你只需要

@PropertySource("/WEB-INF/conf/mars.properties")

Spring 将使用 DefaultResourceLoader#getResource(String)。对于以 / 开头的路径,这委托给 getResourceByPath,它被 AbstractRefreshableWebApplicationContext(处理 @ConfigurationAnnotationConfigWebApplicationContext 的超类)覆盖。

这将创建一个 ServletContextResource 可以成功定位相对于 servlet 上下文的资源。