coder
coder

Reputation: 1941

Reading from properties file in spring

I have a web application in which I'm using spring MVC. I have defined few constants in sample.properties file. spring-servlet is the servlet that gets initialized for all urls in my app. spring-servlet:

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
    <context:property-placeholder location="classpath:sample.properties"/>
</beans>

In one of my java classes I access the value of one of the properties like this:

package com.sample;

import com.google.gson.JsonArray;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Validator {

    @Value("${credit}")
    String credits;

    private static final Logger LOG = Logger.getLogger(Validator.class);

    public void checkRating() {
        LOG.debug(credits);
    }
}

sample.properties:

credit=[{"duration":15,"credit":10},{"duration":30,"credit":20}]

When Validator is called from a controller, it just logs it as ${credit} in my log file. I dont get its value. Similarly, if I put an integer / floating point number in the properties file, I get an error saying it cannot be cast into integer / float. Am I missing any configuration?

Upvotes: 0

Views: 431

Answers (1)

Shailendra
Shailendra

Reputation: 9102

The reason for this is because propertyplaceholder configurer is a BeanFactoryPostProcessor and it processess only the beans defined in the context in which the propertyplaceholder is configured. In a web application typically there is a heirarchy of context as explained here. Hence you need to declare this at appropriate place.

Upvotes: 1

Related Questions