SpringBoot:四种读取properties文件的方式
前言
在项目开发中经常会用到配置文件,配置文件的存在解决了很大一份重复的工作。今天就分享四种在Springboot中获取配置文件的方式。
注:前三种测试配置文件为springboot默认的application.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方式
自定义配置类:PropertiesConfig.java
- 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 battle
- * @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
- 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;
- @SpringBootApplication
- @RestController
- public class Applaction {
- @Autowired private PropertiesConfig propertiesConfig;
- /**
- * 第一种方式:使用`@ConfigurationProperties`注解将配置文件属性注入到配置对象类中
- * @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":"admin",
"callback":"http://www.flyat.cc","password":"123456"},
"type":"Springboot - @ConfigurationProperties"}
二、使用@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 * @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.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`的方式 * * @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.battle.name":"zyd",
- "com.battle.address":"Beijing",
- "com.battle.title":"使用Listeners + PropertiesLoaderUtils获取配置文件",
- "com.battle.type":"Springboot - Listeners",
- "com.battle.company":"in"}
转载于:https://www.cnblogs.com/muliu/p/8252971.html
SpringBoot:四种读取properties文件的方式相关推荐
- Python四种读取数据文件的方法
下面介绍读取数据文件的方法: 首先说明下数据文件的格式 第一行为列名,第一列为编号 第一种:手写读取数据 f = file(路径名)x = []y = []for i, d in enumerate( ...
- JAVA读取Properties文件对象常用方法总结
实际开发中,总是会需要用到配置文件的,常用的就是properties.xml.json.比如,使用jdbc访问数据库时,我们就可以将driver.url.username.password这几个参数记 ...
- java中读取properties文件内容五种方式
一.背景 最近,在项目开发的过程中,遇到需要在properties文件中定义一些自定义的变量,以供java程序动态的读取,修改变量,不再需要修改代码的问题.就借此机会把Spring+SpringMVC ...
- 五种方式让你在java中读取properties文件内容不再是难题
2019独角兽企业重金招聘Python工程师标准>>> 方式1.通过context:property-placeholder加载配置文件jdbc.properties中的内容 < ...
- SpringBoot读取properties文件中的值
SpringBoot读取properties文件中的值 properties文件(test.properties) xx.xyz.url=http://www.xxx.com/ xx.xyz.name ...
- SpringMVC通过注解方式读取properties文件中的值
为什么80%的码农都做不了架构师?>>> 本方法是结合Java配置及XML配置来完成. 首先定义XML配置文件 app.xml: <?xml version=" ...
- SpringBoot使用@Value读取.properties中文乱码及解决方法
问题重现 某不知名springboot小项目,application.properties文件: custom.param=中文属性值 java代码: @SpringBootApplication p ...
- java读取mysql数据库配置文件_java读取properties文件的方法
Java 读写Properties配置文件 Java 读写Properties配置文件 1.Properties类与Properties配置文件 Properties类继承自Hashtable类并且实 ...
- 读取properties文件
为什么80%的码农都做不了架构师?>>> Java 开发中,需要将一些易变的配置参数放置再 XML 配置文件或者 properties 配置文件中.然而 XML 配置文件需要通 ...
最新文章
- Python学习心得第一周-03练习2
- jquery-validate remote验证,返回不同的消息内容
- shell脚本的测试与判断的基础实施
- [译]开始对Angular App进行单元测试(1)
- linux 的重定向、管道、xargs 命令
- OpenWrt配置篇
- ubuntu连不上wifi解决办法
- 开源API网关系统:Kong简介
- 微信发红包的测试用例
- LOL手游诺手终极玩法,对线王者剑姬如何操作?国服第一推荐操作
- iOS和Android和H5交互WebViewJavascriptBridge
- 女生学python工作累吗_数据分析师女生做累么 工资一般多少
- 2021电赛国一——K题照度稳定可调LED台灯
- JS实现飞行的小鸟游戏-简易版
- 《卓有成效的管理者》阅读心得
- Forkast News对话节目 | 中国的BSN将如何改变区块链?
- 【千寻位置前端校招笔试、一面、二面】
- 当网红本人成为网红毒瘤:Vtuber的纸片人模式能够破解困局吗?
- 机器人快跑!伯克利和CMU联合开发两足机器人,两条细腿,一马平川
- c语言编程 0-6的数字对应星期,输入一个数字0~6 用中英文显示星期几 如何用vb编程...
热门文章
- iOS项目中引入pod管理工具
- Windows Service编程
- IPV4和IPV6报头对比分析
- 数据分析36计(16):和 A/B 测试同等重要的观察性研究:群组研究 VS 病例-对照方法...
- 【开源项目】Smart,让魅族Smartbar变得Smart,Version:2.0
- MXNet入门之数据操作
- Kotlin -正确退出forEach
- mysql日期格式化 yyyymmdd_mysql中时间日期格式化
- iOS CALayer anchorPoint 的应用场景
- 基于深度强化学习的智能汽车决策模型