0

I would like to override the getProperty() method in java.util.Properties class ,Please advise.

1.Spring Context file

spring-context.xml

    <bean id="myproperty" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
            <property name="locations" value="classpath:myproperties.properties" />

</bean> 

2. Java Class

public class MyClass{

      @Autowired
        public void setMyproperty(Properties myproperty) {
             this.url=myproperty.getProperty("url");
         }

    }

3.Config file

myproperties.properties
url=http://stackoverflow.com

Fyi : I am pulling out lot values from config file and i would like to invoke trim() once i get the value from .properties, to avoid code redundancy trying to override the getProperty() method.

Using :Spring 4.0

Vasanth
  • 474
  • 2
  • 9
  • 31

1 Answers1

1

Extend the spring default property placeholder (PropertyPlaceholderConfigurer) and capture the properties it loads in the local variable.

public class PropertiesUtils extends PropertyPlaceholderConfigurer {

    private static Map<String, String> propertiesMap;
    private int springSystemPropertiesMode = SYSTEM_PROPERTIES_MODE_FALLBACK;

    @Override
    public void setSystemPropertiesMode(int systemPropertiesMode) {
        super.setSystemPropertiesMode(systemPropertiesMode);
        springSystemPropertiesMode = systemPropertiesMode;
    }

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException {
        super.processProperties(beanFactory, props);

        propertiesMap = new HashMap<String, String>();
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            String valueStr = resolvePlaceholder(keyStr, props, springSystemPropertiesMode);
            propertiesMap.put(keyStr, valueStr);
        }
    }

    public static String getProperty(String name) {
        return propertiesMap.get(name).toString();
    }
Sai prateek
  • 11,842
  • 9
  • 51
  • 66