spring 函数式获取properties配置文件属性的值

在加了 <context:property-placeholder location="classpath*:*.properties"/>后,这种@Value("${name}") 等注解式就可以获取属性值,但是有些场景想要用函数式方式获取属性值,如:getValueByKey(String key)。两步骤即可实现

1.继承PropertyPlaceholderConfigurer 拿到Properties

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.util.Properties;

public class PropertyPlaceholderConfigurerHelper extends PropertyPlaceholderConfigurer {

    private Properties props;

    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
        super.processProperties(beanFactoryToProcess,props);
        this.props = props;
    }

    public String get(String key){
        return props.getProperty(key);
    }
}

2.添加托管的properties的文件

    <bean id="propertyPlaceholderConfigurerHelper" class="com.demo.helper.PropertyPlaceholderConfigurerHelper">
        <property name="ignoreResourceNotFound" value="true"/>
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="locations">
            <list>
                <value>classpath*:my.properties</value>
                <value>classpath*:my1.properties</value>
            </list>
        </property>
    </bean>

猜你喜欢

转载自blog.csdn.net/ilovec1/article/details/88290911