在 springboot 中, 每次启动 main 方法, 程序都会自动加载 application.properties 或者 application.yml 这两个文件
#######################方式一#########################
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")
// 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
@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
@SpringBootApplication
@RestController
public class Applaction {
@Value("${com.zyd.type}")
private String type;
@Value("${com.zyd.title}")
private String title;
/**
*
* 第二种方式:使用`@Value("${propertyName}")`注解
*
* @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
@SpringBootApplication
@RestController
public class Applaction {
@Autowired
private Environment env;
/**
*
* 第三种方式:使用`Environment`
* @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"}
四、使用EnvironmentPostProcessor 重点介绍
前面三种方式都是程序自主就可以加载,在实际项目中,有很多自定义的文件需要加载,把项目打包成 jar 通过 java -jar xxx.jar 运行的时候可以通过在主程序中添加监听器的方式加载,但是生产环境下,
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(ServletInitializer.class);
}
public static void main(String[] args) {
SpringApplication application = new SpringApplication(ServletInitializer.class);
application.addListeners(new PropertiesListener("xxxx.properties"));
application.run(args);
}
}
public class PropertiesListener implements ApplicationListener<ApplicationStartingEvent> {
private String propertiesFileName;
public PropertiesListener (String propertiesFileName) {
this.propertiesFileName = propertiesFileName;
}
@Override
public void onApplicationEvent(ApplicationStartingEvent event) {
PropertiesListenerConfig.loadAllProperties(propertiesFileName);
}
}
war 启动是通过 tomcat 的方式启动那么通过监听器的方式就没效果了
通过实现 EnvironmentPostProcessor 在程序启动加载程序环境的时候加载自定义的属性文件
package com.dzj.exx.main.util;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import listener.PropertiesListenerConfig;
/**
* @ClassName:
* @Description:
* @author 杨云
* @date 下午2:50:54
*/
public class LocalSettingsEnvironmentPostProcessor implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
PropertiesListenerConfig.loadAllProperties("app-config-dev.properties");
}
}
package listener;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.springframework.core.io.support.PropertiesLoaderUtils;
/**
* 加载属性文件内容
* @ClassName:
* @Description:
* @author 杨云
* @date 上午10:27:40
*/
public class PropertiesListenerConfig {
public static Map<String, String> propertiesMap = new HashMap<>();
private static void processPropesties(Properties props) {
propertiesMap = new HashMap<>();
for (Object key : props.keySet()) {
String keyStr = key.toString();
try {
// PropertiesLoaderUtils 默认 iso-8895-1 编码
propertiesMap.put(keyStr, new String(props.getProperty(keyStr).getBytes("ISO-8859-1")));
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void loadAllProperties(String propertiesFileName) {
try {
Properties properties = PropertiesLoaderUtils.loadAllProperties(propertiesFileName);
processPropesties(properties);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @Description: 通过属性名获取对应的值
* @param name
* @return
* @time: 2018年9月1日
* @author 杨云
*/
public static String getProperties(String name) {
return propertiesMap.get(name);
}
/**
* @Description: 获取整个文件的 map 结构的数据结构
* @return
* @time: 2018年9月1日
* @author 杨云
*/
public static Map<String, String> getAllProperties(){
return propertiesMap;
}
}
在程序用可以通过 PropertiesListenerConfig.getProperties(fieldName); 获取对应的值
最后需要配置 LocalSettingsEnvironmentPostProcessor
org.springframework.boot.env.EnvironmentPostProcessor=com.dzj.exx.main.util.LocalSettingsEnvironmentPostProcessor