电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

SpringBoot四種讀取properties文件的方式(小結)

瀏覽:2日期:2023-05-15 16:59:31

前言

在項目開發中經常會用到配置文件,配置文件的存在解決了很大一份重復的工作。今天就分享四種在Springboot中獲取配置文件的方式。

注:前三種測試配置文件為springboot默認的application.properties文件

#######################方式一#########################com.zyd.type3=Springboot - @ConfigurationPropertiescom.zyd.title3=使用@ConfigurationProperties獲取配置文件#mapcom.zyd.login[username]=zhangdeshuaicom.zyd.login[password]=zhenshuaicom.zyd.login[callback]=http://www.flyat.cc#listcom.zyd.urls[0]=http://ztool.cccom.zyd.urls[1]=http://ztool.cc/format/jscom.zyd.urls[2]=http://ztool.cc/str2imagecom.zyd.urls[3]=http://ztool.cc/json2Entitycom.zyd.urls[4]=http://ztool.cc/ua#######################方式二#########################com.zyd.type=Springboot - @Valuecom.zyd.title=使用@Value獲取配置文件#######################方式三#########################com.zyd.type2=Springboot - Environmentcom.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' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' >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' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' >yadong.zhang</a> * @date 2017年6月1日 下午3:49:30 * @version V1.0 * @since JDK : 1.7 */@SpringBootApplication@RestControllerpublic 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

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' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' >yadong.zhang</a> * @date 2017年6月1日 下午3:49:30 * @version V1.0 * @since JDK : 1.7 */@SpringBootApplication@RestControllerpublic 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' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' >yadong.zhang</a> * @date 2017年6月1日 下午3:49:30 * @version V1.0 * @since JDK : 1.7 */@SpringBootApplication@RestControllerpublic 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.zyd.type=Springboot - Listenerscom.zyd.title=使用Listeners + PropertiesLoaderUtils獲取配置文件com.zyd.name=zydcom.zyd.address=Beijingcom.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' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' >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; } @Override public 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' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' >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' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' rel='external nofollow' >yadong.zhang</a> * @date 2017年6月1日 下午3:49:30 * @version V1.0 * @since JDK : 1.7 */@SpringBootApplication@RestControllerpublic 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'}

到此這篇關于SpringBoot四種讀取properties文件的方式(小結)的文章就介紹到這了,更多相關SpringBoot讀取properties文件內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
主站蜘蛛池模板: 奶茶加盟,奶茶加盟店连锁品牌-甜啦啦官网 | 湖南自考_湖南自学考试 | 西安标准厂房_陕西工业厂房_西咸新区独栋厂房_长信科技产业园官方网站 | 智能气瓶柜(大型气瓶储存柜)百科 | 扒渣机厂家_扒渣机价格_矿用扒渣机_铣挖机_撬毛台车_襄阳永力通扒渣机公司 | 交变/复合盐雾试验箱-高低温冲击试验箱_安奈设备产品供应杭州/江苏南京/安徽马鞍山合肥等全国各地 | 软文发布-新闻发布推广平台-代写文章-网络广告营销-自助发稿公司媒介星 | 中图网(原中国图书网):网上书店,尾货特色书店,30万种特价书低至2折! | 西点培训学校_法式西点培训班_西点师培训_西点蛋糕培训-广州烘趣西点烘焙培训学院 | 耙式干燥机_真空耙式干燥机厂家-无锡鹏茂化工装备有限公司 | 不锈钢电动球阀_气动高压闸阀_旋塞疏水调节阀_全立阀门-来自温州工业阀门巨头企业 | 安平县鑫川金属丝网制品有限公司,声屏障,高速声屏障,百叶孔声屏障,大弧形声屏障,凹凸穿孔声屏障,铁路声屏障,顶部弧形声屏障,玻璃钢吸音板 | 广州展览制作|展台制作工厂|展览设计制作|展览展示制作|搭建制作公司 | 无线联网门锁|校园联网门锁|学校智能门锁|公租房智能门锁|保障房管理系统-KEENZY中科易安 | 排烟防火阀-消防排烟风机-正压送风口-厂家-价格-哪家好-德州鑫港旺通风设备有限公司 | 浇注料-高铝砖耐火砖-郑州凯瑞得窑炉耐火材料有限公司 | 智能门锁电机_智能门锁离合器_智能门锁电机厂家-温州劲力智能科技有限公司 | 便携式表面粗糙度仪-彩屏硬度计-分体式粗糙度仪-北京凯达科仪科技有限公司 | 宝鸡市人民医院| 【铜排折弯机,钢丝折弯成型机,汽车发泡钢丝折弯机,线材折弯机厂家,线材成型机,铁线折弯机】贝朗折弯机厂家_东莞市贝朗自动化设备有限公司 | SMC-ASCO-CKD气缸-FESTO-MAC电磁阀-上海天筹自动化设备官网 | 步进_伺服_行星减速机,微型直流电机,大功率直流电机-淄博冠意传动机械 | 学叉车培训|叉车证报名|叉车查询|叉车证怎么考-工程机械培训网 | 济南ISO9000认证咨询代理公司,ISO9001认证,CMA实验室认证,ISO/TS16949认证,服务体系认证,资产管理体系认证,SC食品生产许可证- 济南创远企业管理咨询有限公司 郑州电线电缆厂家-防火|低压|低烟无卤电缆-河南明星电缆 | 上海盐水喷雾试验机_两厢式冷热冲击试验箱-巨怡环试 | 环氧树脂地坪_防静电地坪漆_环氧地坪漆涂料厂家-地壹涂料地坪漆 环球电气之家-中国专业电气电子产品行业服务网站! | 手术室净化装修-手术室净化工程公司-华锐手术室净化厂家 | 订做不锈钢_不锈钢定做加工厂_不锈钢非标定制-重庆侨峰金属加工厂 | 双齿辊破碎机-大型狼牙破碎机视频-对辊破碎机价格/型号图片-金联机械设备生产厂家 | 南方珠江-南方一线电缆-南方珠江科技电缆-南方珠江科技有限公司 南汇8424西瓜_南汇玉菇甜瓜-南汇水蜜桃价格 | 防伪溯源|防窜货|微信二维码营销|兆信_行业内领先的防伪防窜货数字化营销解决方案供应商 | 辊道窑炉,辊道窑炉厂家-山东艾希尔| 电动车头盔厂家_赠品头盔_安全帽批发_山东摩托车头盔—临沂承福头盔 | 桨叶搅拌机_螺旋挤压/方盒旋切造粒机厂家-无锡市鸿诚输送机械有限公司 | loft装修,上海嘉定酒店式公寓装修公司—曼城装饰 | 冷藏车厂家|冷藏车价格|小型冷藏车|散装饲料车厂家|程力专用汽车股份有限公司销售十二分公司 | 东莞市踏板石餐饮管理有限公司_正宗桂林米粉_正宗桂林米粉加盟_桂林米粉加盟费-东莞市棒子桂林米粉 | 混合反应量热仪-高温高压量热仪-微机差热分析仪DTA|凯璞百科 | 成都中天自动化控制技术有限公司| 液晶拼接屏厂家_拼接屏品牌_拼接屏价格_监控大屏—北京维康 | 金属雕花板_厂家直销_价格低-山东慧诚建筑材料有限公司 |