kmansoor
kmansoor

Reputation: 4345

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

Spring version 4.2.2: What would be the Java Config replacement for the following:

<bean id="placeholderConfig"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="/WEB-INF/conf/mars.properties" />
</bean>

I have the following in one of the Config. files:

@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));
....
}

This results in the following runtime error:

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)

I tried the following variations but to no avail:

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

This is an XML configured based application I'm converting to Java Config.

Upvotes: 2

Views: 6916

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279880

All you need is

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

Spring will use DefaultResourceLoader#getResource(String). For paths starting with /, this delegates to getResourceByPath which is overriden by AbstractRefreshableWebApplicationContext (the superclass of AnnotationConfigWebApplicationContext which handles @Configuration).

This will then create a ServletContextResource which can successfully locate the resource relative to the servlet context.

Upvotes: 3

Related Questions