【Java Web開發學習】Spring加載外部properties配置文件
轉載:https://www.cnblogs.com/yangchongxing/p/9136505.html
1、聲明屬性源,通過Spring的Environment檢索來裝配屬性
Environment檢索的值來源於屬性源,直接從Environment中檢索屬性是非常方便的,尤其在Java配置中裝配Bean的時候,。
package com.qq.weixin.mp.config; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; @Configuration @PropertySource(value="classpath:weixin.properties")//屬性源,maven配置位於src\main\resources目錄下 public class WeixinConfig { private String appid; private String appsecret; @Autowired Environment env; @Bean public Map<String, String> config() { appid = env.getProperty("appid");//檢索屬性 appsecret = env.getProperty("appsecret");//檢索屬性 Map<String, String> map = new HashMap<String, String>(); map.put("appid", appid); map.put("appsecret", appsecret); return map; } }
2、有配置類,通過占位符來裝配屬性
占位符的值來源於屬性源,占位符的形式為使用${...}包裝的屬性名稱。
package com.qq.weixin.mp.config; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration @PropertySource(value="classpath:weixin.properties")//屬性源 public class WeixinConfig { @Value("${appid}")//占位符 private String appid; @Value("${appsecret}") private String appsecret; @Bean public Map<String, String> config() { Map<String, String> map = new HashMap<String, String>(); map.put("appid", appid); map.put("appsecret", appsecret); return map; } }
或者定義PropertySourcesPlaceholderConfigurer Bean Spring3.1以后推薦使用
@Bean public PropertySourcesPlaceholderConfigurer placeholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); }
<context:property-placeholder />