如何在春季覆盖PropertiesFactoryBean?

时间:2018-09-08 05:55:55

标签: java spring el

我想重写java.util.Properties类中的getProperty()方法,请告知。

1.Spring上下文文件

spring-context.xml

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

</bean> 

2。 Java类

public class MyClass{

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

    }

3.Config文件

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

Fyi:我正在从配置文件中提取很多值,一旦我从.properties中获取值,我想调用trim(),以避免试图覆盖getProperty()方法的代码冗余。

使用:Spring 4.0

1 个答案:

答案 0 :(得分:0)

扩展spring默认属性占位符(PropertyPlaceholderConfigurer),并捕获它在局部变量中加载的属性。

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();
    }