Eedoh
Eedoh

Reputation: 6288

How to read properties (or any other text) file in Java Spring MVC app?

I need to read java properties file inside my Spring MVC app but I can't find the way to do that. I tried several answers from similar question here on SO, but I was unsuccessful. I'm new to Java, and especially Spring MVC so I probably messed up something.

I'm not sure anymore that the file is being successfully deployed. I'm using Tomcat btw.

Upvotes: 4

Views: 39960

Answers (3)

Santosh Hegde
Santosh Hegde

Reputation: 3520

You can try the below code.

Add this to servelt-context.xml

<context:property-placeholder location="classpath:config.properties"/>

And to access the contents of config file in java,

@Value("${KEY}")
private String value;

Upvotes: 1

matsev
matsev

Reputation: 33797

If you are using Spring 3.1+ you can use the @PropertySource annotation:

@Configuration
@PropertySource("classpath:/com/example/app.properties")
public class AppConfig {
    // create beans
}

or for XML-based configuration you can use the <context:property-placeholder>:

<beans>
    <context:property-placeholder location="classpath:com/example/app.properties"/>
    <!-- bean declarations -->
</beans>

then you can autowire the key in the properties file using the @Value annotation:

@Value("${property.key}") String propertyValue;

Read more details in the Spring reference docs.

Upvotes: 11

gregwhitaker
gregwhitaker

Reputation: 13420

You can have properties files automatically loaded in Spring by using the PropertySourcesPlaceholderConfigurer.

Here is an example of configuring a PropertySourcesPlaceholderConfigurer using Spring JavaConfig:

@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
    PropertySourcesPlaceholderConfigurer props = new PropertySourcesPlaceholderConfigurer();
    props.setLocations(new Resource[] {
            new ClassPathResource("/config/myconfig.properties"),
            new ClassPathResource("version.properties")
    });
}

This will load the properties from the files above on the classpath.

You can use these properties in property replacements within your application. For example, assume that there is a property in one of those files above named myprop. You could inject myprop's value into a field using the following:

@Value(${myprop})
private String someProperty;

You can also access the values of the properties by injecting Spring's Environment object into your classes.

@Resource
private Environment environment;

public void doSomething() {
   String myPropValue = environment.getProperty("myprop");
}

In order to read any old file from within a web application the link that Frederic posted in the comments above provides a good explanation of the normal classloader hurdles one encounters when attempting to read files from within their war file and the solutions around it.

Upvotes: 3

Related Questions