/** * Created by ywq on 2016/6/30. */ @Named public class PropertyConfig { private static AbstractBeanFactory beanFactory = null; private static final Map<String,String> cache = new oncurrentHashMap<>(); @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");