經過spring工廠讀取property配置文件

/**
 * Created by ywq on 2016/6/30.
 */
@Named
public class PropertyConfig {

    private static AbstractBeanFactory beanFactory = null;

    private static final Map<String,String> cache = new ConcurrentHashMap<>();

    @Inject
    public PropertyConfig(AbstractBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    /**
     * 根據key獲取配置文件的Value
     * @param key
     * @return
     */
    public static String getProperty(String key) {
        String propValue = "";
        if(cache.containsKey(key)){
            propValue = cache.get(key);
        } else {
            try {
                propValue = beanFactory.resolveEmbeddedValue("${" + key.trim() + "}");
                cache.put(key,propValue);
            } catch (IllegalArgumentException ex) {
                ex.printStackTrace();
            }
        }
        return propValue;
    }
}
Spring xml的配置
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
    <property name="ignoreResourceNotFound" value="true"/>
    <property name="locations">
        <list>
            <value>classpath:props/${property-path}.properties</value>
            <value>classpath:important.properties</value>
        </list>
    </property>
</bean>
在項目中使用
String maxTimeInSecondsProp = PropertyConfig.getProperty("maxTimeInSeconds");
相關文章
相關標籤/搜索