spring 函数式获取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的文件

    
        
        
        
            
                classpath*:my.properties
                classpath*:my1.properties
            
        
    

 

你可能感兴趣的:(spring 函数式获取properties配置文件属性的值)