概述
SpringBoot工程默认读取application.properties配置文件
在Springboot中获取配置文件的方式
方式二和方式三测试配置文件为springboot默认的application.properties文件
application.properties文件:
# 方式一
com.hi.type3=Springboot - @ConfigurationProperties
com.hi.title3=使用@ConfigurationProperties获取配置文件
#map
com.hi.login[username]=nameConfigurationProperties
com.hi.login[password]=passwordConfigurationProperties
com.hi.login[callback]=http://www.baidu.com
#list
com.hi.urls[0]=http://123.com
com.hi.urls[1]=http://1234.com
com.hi.urls[2]=http://12345.com
com.hi.urls[3]=http://12346.com
com.hi.urls[4]=http://12347.com
# 方式二
com.hi.type=Springboot - @Value
com.hi.title=使用@Value获取配置文件
# 方式三
com.hi.type2=Springboot - Environment
com.hi.title2=使用Environment获取配置文件
方式一(@ConfigurationProperties方式)
配置类编写
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.stereotype.Component;
@Component//标识为Bean
//prefix用来选择属性的前缀,也就是在remote.properties文件中的“com.hi”
@ConfigurationProperties(prefix = "com.hi")
//说明配置文件路径是config/remote.properties
@PropertySource("classpath:config/remote.properties")
//lombok注解,用于生成getter&setter方法
@Data
public class PropertiesConfig {
public String type3;
public String title3;
public Map<String, String> login = new HashMap<String, String>();
public List<String> urls = new ArrayList<>();
}
使用
在想要使用配置文件的方法所在类上表上注解EnableConfigurationProperties(RemoteProperties.class)
并使用@Autowired自动注入
如下:
@EnableConfigurationProperties(propertiesConfig.class)
@RestController
public class Test{
@Autowired
private PropertiesConfig propertiesConfig;
@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;
}
}
返回结果如下(我格式化过):
{
"title": "使用@ConfigurationProperties获取配置文件",
"urls": [
"http://123.com",
"http://1234.com",
"http://12345.com",
"http://12346.com",
"http://12347.com"
],
"login": {
"username": "nameConfigurationProperties",
"callback": "http://www.baidu.com",
"password": "passwordConfigurationProperties"
},
"type": "Springboot - @ConfigurationProperties"
}
方式二(使用@Value注解方式)
写一个controller
@Value("${com.hi.type}")
private String type;
@Value("${com.hi.title}")
private String title;
@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;
}
返回结果如下(我格式化过):
{
"title": "使用@Value获取配置文件",
"type": "Springboot - @Value"
}
方式三(使用Environment)
@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.hi.type2"));
map.put("title", new String(env.getProperty("com.hi.title2").getBytes("ISO-8859-1"), "UTF-8"));
return map;
}
返回结果如下(我格式化过):
{
"title": "使用Environment获取配置文件",
"type": "Springboot - Environment"
}
方式四(使用PropertiesLoaderUtils+Listeners)
配置文件
获取这个配置文件的内容:app-config.properties
#### 通过注册监听器(`Listeners`) + `PropertiesLoaderUtils`的方式
com.hi.type=Springboot - Listeners
com.hi.title=使用Listeners + PropertiesLoaderUtils获取配置文件
com.hi.name=namePropertiesLoaderUtils+Listeners
com.hi.address=abc
com.hi.company=in
PropertiesListener
PropertiesListener.java:用来初始化加载配置文件
即下面这个类
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import com.hi.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
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;
}
}
执行
使用controller去访问,获取内容
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.hi.property.config.PropertiesListenerConfig;
import com.hi.property.listener.PropertiesListener;
@SpringBootApplication
@RestController
public class Applaction {
@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": "namePropertiesLoaderUtils+Listeners",
"com.zyd.address": "abc",
"com.zyd.title": "使用Listeners + PropertiesLoaderUtils获取配置文件",
"com.zyd.type": "Springboot - Listeners",
"com.zyd.company": "in"
}