前言

在项目开发中经常会用到配置文件,配置文件的存在解决了很大一份重复的工作。今天就分享四种在Springboot中获取配置文件的方式。


注:前三种测试配置文件为springboot默认的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

package com.zyd.property.config;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 <a href="mailto:yadong.zhang0415@gmail.com">yadong.zhang</a>* @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

package com.zyd.property;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;/*** @author <a href="mailto:yadong.zhang0415@gmail.com">yadong.zhang</a>* @date 2017年6月1日 下午3:49:30 * @version V1.0* @since JDK : 1.7*/
@SpringBootApplication
@RestController
public class Applaction {@Autowiredprivate 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

package com.zyd.property;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;/*** @author <a href="mailto:yadong.zhang0415@gmail.com">yadong.zhang</a>* @date 2017年6月1日 下午3:49:30 * @version V1.0* @since JDK : 1.7*/
@SpringBootApplication
@RestController
public class Applaction {@Value("${com.zyd.type}")private String type;@Value("${com.zyd.title}")private String title;/*** * 第二种方式:使用`@Value("${propertyName}")`注解* * @author zyd* @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

package com.zyd.property;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;/*** @author <a href="mailto:yadong.zhang0415@gmail.com">yadong.zhang</a>* @date 2017年6月1日 下午3:49:30* @version V1.0* @since JDK : 1.7*/
@SpringBootApplication
@RestController
public class Applaction {@Autowiredprivate 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.zyd.type=Springboot - Listeners
com.zyd.title=使用Listeners + PropertiesLoaderUtils获取配置文件
com.zyd.name=zyd
com.zyd.address=Beijing
com.zyd.company=in

PropertiesListener.java 用来初始化加载配置文件

package com.zyd.property.listener;import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;import com.zyd.property.config.PropertiesListenerConfig;/*** 配置文件监听器,用来加载自定义配置文件* * @author <a href="mailto:yadong.zhang0415@gmail.com">yadong.zhang</a>* @date 2017年6月1日 下午3:38:25 * @version V1.0* @since JDK : 1.7*/
public class PropertiesListener implements ApplicationListener<ApplicationStartedEvent> {private String propertyFileName;public PropertiesListener(String propertyFileName) {this.propertyFileName = propertyFileName;}@Overridepublic void onApplicationEvent(ApplicationStartedEvent event) {PropertiesListenerConfig.loadAllProperties(propertyFileName);}
}

PropertiesListenerConfig.java 加载配置文件内容

package com.zyd.property.config;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;/*** 第四种方式:PropertiesLoaderUtils* * @author <a href="mailto:yadong.zhang0415@gmail.com">yadong.zhang</a>* @date 2017年6月1日 下午3:32:37* @version V1.0* @since JDK : 1.7*/
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 启动类

package com.zyd.property;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;/*** @author <a href="mailto:yadong.zhang0415@gmail.com">yadong.zhang</a>* @date 2017年6月1日 下午3:49:30 * @version V1.0* @since JDK : 1.7*/
@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.zyd.name":"zyd","com.zyd.address":"Beijing","com.zyd.title":"使用Listeners + PropertiesLoaderUtils获取配置文件","com.zyd.type":"Springboot - Listeners","com.zyd.company":"in"}

详细代码请移步:Github源码

转载:https://www.imooc.com/article/18252

SpringBoot项目 四种读取properties文件的方式相关推荐

  1. SpringBoot:四种读取properties文件的方式

    前言 在项目开发中经常会用到配置文件,配置文件的存在解决了很大一份重复的工作.今天就分享四种在Springboot中获取配置文件的方式. 注:前三种测试配置文件为springboot默认的applic ...

  2. Python四种读取数据文件的方法

    下面介绍读取数据文件的方法: 首先说明下数据文件的格式 第一行为列名,第一列为编号 第一种:手写读取数据 f = file(路径名)x = []y = []for i, d in enumerate( ...

  3. idea中spark项目Scala语言读取properties文件

    1.将文件放入resources目录下面,将文件设置成resources file->Project Structure->Modules 选择文件,然后点击resources 2.在类中 ...

  4. JAVA读取Properties文件对象常用方法总结

    实际开发中,总是会需要用到配置文件的,常用的就是properties.xml.json.比如,使用jdbc访问数据库时,我们就可以将driver.url.username.password这几个参数记 ...

  5. java中读取properties文件内容五种方式

    一.背景 最近,在项目开发的过程中,遇到需要在properties文件中定义一些自定义的变量,以供java程序动态的读取,修改变量,不再需要修改代码的问题.就借此机会把Spring+SpringMVC ...

  6. 五种方式让你在java中读取properties文件内容不再是难题

    2019独角兽企业重金招聘Python工程师标准>>> 方式1.通过context:property-placeholder加载配置文件jdbc.properties中的内容 < ...

  7. Java项目中读取properties文件,以及六种获取路径的方法

    下面1-4的内容是网上收集的相关知识,总结来说,就是如下几个知识点: 最常用读取properties文件的方法 InputStream in = getClass().getResourceAsStr ...

  8. Java项目中读取properties文件

    下面1-4的内容是网上收集的相关知识,总结来说,就是如下几个知识点: 最常用读取properties文件的方法 InputStream in = getClass().getResourceAsStr ...

  9. java 遍历属性文件路径_Java项目中读取properties文件,以及六种获取路径的方法...

    Java读取properties文件的方法比较多,网上最多的文章是"Java读取properties文件的六种方法",但在Java应用中,最常用还是通过java.lang.Clas ...

  10. SpringBoot读取properties文件中的值

    SpringBoot读取properties文件中的值 properties文件(test.properties) xx.xyz.url=http://www.xxx.com/ xx.xyz.name ...

最新文章

  1. 给热爱学习的同学们推荐一些顶级的c# Blogs链接
  2. 独家对话阿里云函数计算负责人不瞋:你所不知道的 Serverless
  3. Boost:容器std::pair与宏BOOST_TEST_EQ相关的测试
  4. 人工智能,不止于技术的革命--WOT2017全球创新技术峰会开幕
  5. IntelliJ IDEA for Mac在MacOS模式下的调试快捷键(Debugging Shortcut)
  6. 【汇编语言】数据类型的匹配问题:自动匹配与手动匹配
  7. Laravel核心解读 -- 事件系统
  8. python发音模块-python 利用pyttsx3文字转语音过程详解
  9. [转载]java对cookie的操作
  10. ubuntu 发布asp.net 站点(.net core)
  11. 三问智能体,华为如何落地全场景智慧
  12. 移植wpa_supplicant-2.2
  13. cpu利用率(cpu利用率突然100)
  14. 如何将图片压缩到15k以下?教你一键压缩图片的大小
  15. 警惕 CONFIG+=ordered
  16. C++ 动态库导出函数名乱码及解决
  17. 2021年N1叉车司机模拟考试及N1叉车司机证考试
  18. Android Studio 获取经纬度
  19. php开发的抽奖系统源码,幸运九宫格类型的,带后台可控制
  20. 小程序微信支付功能逻辑

热门文章

  1. 如何使用多种方法在 Mac 上截屏?
  2. 国内坐标转换常用投影EPSG
  3. 日语简体形与敬体形 - 新版标日22课
  4. ES6(ECMAScript6)知识总结(二)
  5. 英雄联盟一直连接服务器win10,浅析win10英雄联盟连接不上服务器的解决教程
  6. 高德地图获取经纬度工具类
  7. ArduinoUNO实战-第十八章-三基色LED实现七彩色渐变
  8. SkipList A Probabilistic Alternative to Balanced Trees
  9. 计算机光盘无法格式化,win10无法格式化dvd光盘
  10. 怎么找到使用驱动器中的光盘之前需要将其格式化磁盘的数据