spring启动时会通过
<beans profile="env"> <context:property-placeholder ignore-resource-not-found="false" location=" classpath*:XXX.properties"/> </beans>
扫描加载系统中的属性变量,并保存在
applicationContext的beanFactory中的
中,在系统中如果要获取其中的变量可以通过
@Value("${XXXX}")
注入。
或者新建一个类实现java类实现EmbeddedValueResolverAware接口即可获取其中的属性。
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.EmbeddedValueResolverAware; import org.springframework.stereotype.Component; import org.springframework.util.StringValueResolver; /** * 曹鹏程(获取spring中的properties) * Created by caopengcheng on 2016/10/18. */ @Component public class PropertyUtil implements EmbeddedValueResolverAware { private static Log logger = LogFactory.getLog(PropertyUtil.class); private static StringValueResolver stringValueResolver; public static String getProperties(String key){ //获取spring中的属性值 if(stringValueResolver!=null) return stringValueResolver.resolveStringValue("${" + key + "}"); return null; } @Override public void setEmbeddedValueResolver(StringValueResolver resolver) { if(stringValueResolver==null){ this.stringValueResolver=resolver; } } }