参考文章:SpringBoot:四种读取properties文件的方式
配置文件:
#######################方式一#########################
com.battle.type3=Springboot - @ConfigurationProperties
com.battle.title3=使用@ConfigurationProperties获取配置文件
#map
com.battle.login[username]=admin
com.battle.login[password]=123456
com.battle.login[callback]=http://www.flyat.cc
#list
com.battle.urls[0]=http://ztool.cc
com.battle.urls[1]=http://ztool.cc/format/js
com.battle.urls[2]=http://ztool.cc/str2image
com.battle.urls[3]=http://ztool.cc/json2Entity
com.battle.urls[4]=http://ztool.cc/ua
#######################方式二#########################
com.battle.type=Springboot - @Value
com.battle.title=使用@Value获取配置文件
#######################方式三#########################
com.battle.type2=Springboot - Environment
com.battle.title2=使用Environment获取配置文件
一、@ConfigurationProperties方式
1.1 配置文件application.yml
connection.username=admin
connection.password=kyjufskifas2jsfs
connection.remoteAddress=192.168.1.1
1.2 自定义配置类:PropertiesConfig.java
@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {
private String username;
private String remoteAddress;
private String password ;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getRemoteAddress() {
return remoteAddress;
}
public void setRemoteAddress(String remoteAddress) {
this.remoteAddress = remoteAddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
1.3 应用
@SpringBootApplication
public class DemoApplication{
@Bean
@ConfigurationProperties(prefix = "connection")
public ConnectionSettings connectionSettings(){
return new ConnectionSettings();
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@RestController
@RequestMapping("/task")
public class TaskController {
@Autowired ConnectionSettings conn;
@RequestMapping(value = {"/",""})
public String hellTask(){
String userName = conn.getUsername();
return "hello task !!";
}
}
如果发现@ConfigurationPropertie不生效,有可能是项目的目录结构问题,
你可以通过@EnableConfigurationProperties(ConnectionSettings.class)来明确指定需要用哪个实体类来装载配置信息
@Configuration
@EnableConfigurationProperties(ConnectionSettings.class)
public class MailConfiguration {
@Autowired private MailProperties mailProperties;
@Bean public JavaMailSender javaMailSender() {
// omitted for readability
}
}
二、使用@Value注解方式
程序启动类:Applaction.java
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;
@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
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;
/** * * 第三种方式:使用`Environment` * * @author zyd * @throws UnsupportedEncodingException */
@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.battle.type=Springboot - Listeners
com.battle.title=使用Listeners + PropertiesLoaderUtils获取配置文件
com.battle.name=zyd
com.battle.address=Beijing
com.battle.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 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);
}
}
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`的方式*/
@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.battle.name":"zyd",
"com.battle.address":"Beijing",
"com.battle.title":"使用Listeners + PropertiesLoaderUtils获取配置文件",
"com.battle.type":"Springboot - Listeners",
"com.battle.company":"in"}