SpringBoot讀取properties檔案的方式和@Bean註解
阿新 • • 發佈:2019-02-15
application.properties檔案
#######################方式一#########################
com.zyd.type3=Springboot - @ConfigurationProperties
com.zyd.title3=使用@ConfigurationProperties獲取配置檔案
#map
com.zyd.login[username]=zhangdeshuai
com.zyd.login[password]=zhenshuai
com.zyd.login[callback]=http://www.flyat.cc
#list
com .zyd.urls[0]=http://ztool.cc
com.zyd.urls[1]=http://ztool.cc/format/js
com.zyd.urls[2]=http://ztool.cc/str2image
com.zyd.urls[3]=http://ztool.cc/json2Entity
com.zyd.urls[4]=http://ztool.cc/ua
#######################方式二#########################
com.zyd.type=Springboot - @Value
com.zyd.title=使用@Value獲取配置檔案
#######################方式三#########################
com.zyd.type2=Springboot - Environment
com.zyd.title2=使用Environment獲取配置檔案
@ConfigurationProperties註解
自定義配置類:PropertiesConfig.java
@Component
@ConfigurationProperties(prefix = "com.zyd")
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;
}
}
通過@PropertySource可以指定讀取的配置檔案,通過@Value註解獲取值,具體用法:
@Configuration //通過該註解來表明該類是一個Spring的配置,相當於一個xml檔案
@ComponentScan(basePackages = "cn.springboot.javaconfig") //配置掃描包
@PropertySource(value= {"classpath:jdbc.properties"})
public class SpringConfig {
@Value("${jdbc.url}")
private String jdbcUrl;
}
}
如何配置多個配置檔案?
@PropertySource(value= {"classpath:jdbc.properties","xxx.properties"})
如果配置的配置檔案不存在會怎麼樣?
@PropertySource(value= {"classpath:jdbc.properties"},ignoreResourceNotFound=true)
使用Environment
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;
@SpringBootApplication
@RestController
public class Applaction {
@Autowired
private Environment env;
@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);
}
}
使用PropertiesLoadUtils
#### 通過註冊監聽器(`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 用來初始化載入配置檔案
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import com.zyd.property.config.PropertiesListenerConfig;
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 載入配置檔案內容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;
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 啟動類
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;
@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);
}
}