SpringBoot四種讀取properties檔案的方式
阿新 • • 發佈:2018-11-13
原文地址:https://www.imooc.com/article/18252
一、@ConfigurationProperties方式
自定義配置類:PropertiesConfig.java
package com.zyd.property.config; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.boot.context.properties.ConfigurationProperties; //import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; /** * 對應上方配置檔案中的第一段配置 * @author <a href="mailto:
[email protected]">yadong.zhang</a> * @date 2017年6月1日 下午4:34:18 * @version V1.0 * @since JDK : 1.7 */ @Component @ConfigurationProperties(prefix = "com.zyd") // PropertySource預設取application.properties // @PropertySource(value = "config.properties") public class PropertiesConfig { public String type3; public String title3; public Map<String, String> login = new HashMap<String, String>(); public List<String> urls = new ArrayList<>(); public String getType3() { return type3; } public void setType3(String type3) { this.type3 = type3; } public String getTitle3() { try { return new String(title3.getBytes("ISO-8859-1"), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return title3; } public void setTitle3(String title3) { this.title3 = title3; } public Map<String, String> getLogin() { return login; } public void setLogin(Map<String, String> login) { this.login = login; } public List<String> getUrls() { return urls; } public void setUrls(List<String> urls) { this.urls = urls; } }
程式啟動類:Applaction.java
package com.zyd.property;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zyd.property.config.PropertiesConfig;
/**
* @author <a href="mailto: [email protected]">yadong.zhang</a>
* @date 2017年6月1日 下午3:49:30
* @version V1.0
* @since JDK : 1.7
*/
@SpringBootApplication
@RestController
public class Applaction {
@Autowired
private PropertiesConfig propertiesConfig;
/**
*
* 第一種方式:使用`@ConfigurationProperties`註解將配置檔案屬性注入到配置物件類中
*
* @author zyd
* @throws UnsupportedEncodingException
* @since JDK 1.7
*/
@RequestMapping("/config")
public Map<String, Object> configurationProperties() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("type", propertiesConfig.getType3());
map.put("title", propertiesConfig.getTitle3());
map.put("login", propertiesConfig.getLogin());
map.put("urls", propertiesConfig.getUrls());
return map;
}
public static void main(String[] args) throws Exception {
SpringApplication application = new SpringApplication(Applaction.class);
application.run(args);
}
}
訪問結果:
{"title":"使用@ConfigurationProperties獲取配置檔案","urls":["http://ztool.cc","http://ztool.cc/format/js","http://ztool.cc/str2image","http://ztool.cc/json2Entity","http://ztool.cc/ua"],"login":{"username":"zhangdeshuai","callback":"http://www.flyat.cc","password":"zhenshuai"},"type":"Springboot - @ConfigurationProperties"}
二、使用@Value註解方式
程式啟動類:Applaction.java
package com.zyd.property;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author <a href="mailto:[email protected]">yadong.zhang</a>
* @date 2017年6月1日 下午3:49:30
* @version V1.0
* @since JDK : 1.7
*/
@SpringBootApplication
@RestController
public class Applaction {
@Value("${com.zyd.type}")
private String type;
@Value("${com.zyd.title}")
private String title;
/**
*
* 第二種方式:使用`@Value("${propertyName}")`註解
*
* @author zyd
* @throws UnsupportedEncodingException
* @since JDK 1.7
*/
@RequestMapping("/value")
public Map<String, Object> value() throws UnsupportedEncodingException {
Map<String, Object> map = new HashMap<String, Object>();
map.put("type", type);
// *.properties檔案中的中文預設以ISO-8859-1方式編碼,因此需要對中文內容進行重新編碼
map.put("title", new String(title.getBytes("ISO-8859-1"), "UTF-8"));
return map;
}
public static void main(String[] args) throws Exception {
SpringApplication application = new SpringApplication(Applaction.class);
application.run(args);
}
}
訪問結果:
{"title":"使用@Value獲取配置檔案","type":"Springboot - @Value"}
三、使用Environment
程式啟動類:Applaction.java
package com.zyd.property;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author <a href="mailto:[email protected]">yadong.zhang</a>
* @date 2017年6月1日 下午3:49:30
* @version V1.0
* @since JDK : 1.7
*/
@SpringBootApplication
@RestController
public class Applaction {
@Autowired
private Environment env;
/**
*
* 第三種方式:使用`Environment`
*
* @author zyd
* @throws UnsupportedEncodingException
* @since JDK 1.7
*/
@RequestMapping("/env")
public Map<String, Object> env() throws UnsupportedEncodingException {
Map<String, Object> map = new HashMap<String, Object>();
map.put("type", env.getProperty("com.zyd.type2"));
map.put("title", new String(env.getProperty("com.zyd.title2").getBytes("ISO-8859-1"), "UTF-8"));
return map;
}
public static void main(String[] args) throws Exception {
SpringApplication application = new SpringApplication(Applaction.class);
application.run(args);
}
}
訪問結果:
{"title":"使用Environment獲取配置檔案","type":"Springboot - Environment"}
四、使用PropertiesLoaderUtils
app-config.properties
#### 通過註冊監聽器(`Listeners`) + `PropertiesLoaderUtils`的方式
com.zyd.type=Springboot - Listeners
com.zyd.title=使用Listeners + PropertiesLoaderUtils獲取配置檔案
com.zyd.name=zyd
com.zyd.address=Beijing
com.zyd.company=in
PropertiesListener.java 用來初始化載入配置檔案
package com.zyd.property.listener;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import com.zyd.property.config.PropertiesListenerConfig;
/**
* 配置檔案監聽器,用來載入自定義配置檔案
*
* @author <a href="mailto:[email protected]">yadong.zhang</a>
* @date 2017年6月1日 下午3:38:25
* @version V1.0
* @since JDK : 1.7
*/
public class PropertiesListener implements ApplicationListener<ApplicationStartedEvent> {
private String propertyFileName;
public PropertiesListener(String propertyFileName) {
this.propertyFileName = propertyFileName;
}
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
PropertiesListenerConfig.loadAllProperties(propertyFileName);
}
}
PropertiesListenerConfig.java 載入配置檔案內容
package com.zyd.property.config;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.springframework.beans.BeansException;
import org.springframework.core.io.support.PropertiesLoaderUtils;
/**
* 第四種方式:PropertiesLoaderUtils
*
* @author <a href="mailto:[email protected]">yadong.zhang</a>
* @date 2017年6月1日 下午3:32:37
* @version V1.0
* @since JDK : 1.7
*/
public class PropertiesListenerConfig {
public static Map<String, String> propertiesMap = new HashMap<>();
private static void processProperties(Properties props) throws BeansException {
propertiesMap = new HashMap<String, String>();
for (Object key : props.keySet()) {
String keyStr = key.toString();
try {
// PropertiesLoaderUtils的預設編碼是ISO-8859-1,在這裡轉碼一下
propertiesMap.put(keyStr, new String(props.getProperty(keyStr).getBytes("ISO-8859-1"), "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (java.lang.Exception e) {
e.printStackTrace();
}
}
}
public static void loadAllProperties(String propertyFileName) {
try {
Properties properties = PropertiesLoaderUtils.loadAllProperties(propertyFileName);
processProperties(properties);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getProperty(String name) {
return propertiesMap.get(name).toString();
}
public static Map<String, String> getAllProperty() {
return propertiesMap;
}
}
Applaction.java 啟動類
package com.zyd.property;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zyd.property.config.PropertiesListenerConfig;
import com.zyd.property.listener.PropertiesListener;
/**
* @author <a href="mailto:[email protected]">yadong.zhang</a>
* @date 2017年6月1日 下午3:49:30
* @version V1.0
* @since JDK : 1.7
*/
@SpringBootApplication
@RestController
public class Applaction {
/**
*
* 第四種方式:通過註冊監聽器(`Listeners`) + `PropertiesLoaderUtils`的方式
*
* @author zyd
* @throws UnsupportedEncodingException
* @since JDK 1.7
*/
@RequestMapping("/listener")
public Map<String, Object> listener() {
Map<String, Object> map = new HashMap<String, Object>();
map.putAll(PropertiesListenerConfig.getAllProperty());
return map;
}
public static void main(String[] args) throws Exception {
SpringApplication application = new SpringApplication(Applaction.class);
// 第四種方式:註冊監聽器
application.addListeners(new PropertiesListener("app-config.properties"));
application.run(args);
}
}
訪問結果:
{"com.zyd.name":"zyd","com.zyd.address":"Beijing","com.zyd.title":"使用L
作者:慕冬雪
連結:https://www.imooc.com/article/18252
來源:慕課網