SpringBoot如何實(shí)現(xiàn)讀取.config文件
思路分析
這里以IntelliJ IDEA為例:
- 1、創(chuàng)建一個(gè)需要讀取的XML文件數(shù)據(jù)
- 2、建立POJO對(duì)象,將XML數(shù)據(jù)轉(zhuǎn)化為POJO對(duì)象數(shù)據(jù)
- 3、創(chuàng)建一個(gè)XML解析工具類
- 4、創(chuàng)建接口和實(shí)現(xiàn)類
- 5、創(chuàng)建Controller調(diào)用對(duì)應(yīng)的方法執(zhí)行獲取
直接進(jìn)入主題:
- 目標(biāo)文件:后綴為.config的文件
在Java這里需要改為.xml文件,只是后綴發(fā)生改變,內(nèi)容不變。

詳細(xì)操作
1、在resource目錄創(chuàng)建一個(gè)需要讀取的XML文件數(shù)據(jù)

源碼:
<?xml version="1.0" encoding="gb2312"?>
<root>
<mpmenu id="1" title="智能信息" funcId="0202" image="6d0">
<mpmenu id="101" title="問(wèn)題表" image="" funcId="0202" url="p.aspx?t=info_question" />
<mpmenu id="104" title="索引表" image="" funcId="0202" url="p.aspx?t=info_question&typeid=2" />
<mpmenu id="102" title="常見(jiàn)答案" image="" funcId="0202" url="p.aspx?t=info_tree&formname=info_answers" />
<mpmenu id="103" title="專業(yè)內(nèi)容" image="" funcId="0202" url="p.aspx?t=info_tree" />
<mpmenu id="108" title="行業(yè)關(guān)鍵字" image="" funcId="0202" url="p.aspx?t=info_keyback" />
<mpmenu id="105" title="回復(fù)記錄" image="" funcId="0202" url="p.aspx?t=info_qalog_index" />
</mpmenu>
<mpmenu id="2" title="需求管理" funcId="0207" image="616">
<mpmenu id="201" title="待審核" image="" funcId="0207" url="p.aspx?t=unit_require&status=1" />
<mpmenu id="202" title="發(fā)布中" image="" funcId="0207" url="p.aspx?t=unit_require&status=2" />
<mpmenu id="203" title="駁回" image="" funcId="0207" url="p.aspx?t=unit_require&status=3" />
</mpmenu>
<mpmenu id="3" title="商城" funcId="02" image="66a">
<mpmenu id="301" title="商品管理" image="" funcId="0203" url="p.aspx?t=goodslist" />
<mpmenu id="302" title="訂單管理" image="" funcId="0204" url="p.aspx?t=orderlist" />
<mpmenu id="303" title="支付記錄" image="" funcId="0206" url="p.aspx?t=paylog" />
<mpmenu id="304" title="待發(fā)貨" image="" funcId="0205" url="p.aspx?t=toexpress" />
<mpmenu id="305" title="配送記錄" image="" funcId="0205" url="p.aspx?t=expresslog" />
<mpmenu id="320" title="自提點(diǎn)管理" image="" funcId="0203" url="p.aspx?t=self_take_place" />
<mpmenu id="350" title="排行榜" image="" funcId="0203" url="p.aspx?t=mall_ranking" />
</mpmenu>
</root>
2、建立POJO對(duì)象,將XML數(shù)據(jù)轉(zhuǎn)化為POJO對(duì)象數(shù)據(jù)
創(chuàng)建Menudata類,作為父集(xml文件第一層<mpmenu>,即<root>下)。

源碼:
package com.example.business.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.xml.bind.annotation.*;
import java.util.List;
@Data //注在類上,提供類的get、set、equals、hashCode、canEqual、toString方法,需配置lombok依賴
@AllArgsConstructor //注在類上,提供類的全參構(gòu)造
@NoArgsConstructor //注在類上,提供類的無(wú)參構(gòu)造
@XmlRootElement(name = "mpmenu")
@XmlAccessorType(XmlAccessType.FIELD)
public class Menudata {
@XmlAttribute(name = "id")
private String id;
@XmlAttribute(name = "title")
private String title;
@XmlAttribute(name = "image")
private String image;
@XmlAttribute(name = "funcId")
private String funcid;
//用于讀取mpmenu第二層的數(shù)據(jù)
@XmlElement(name = "mpmenu")
private List<Menudatas> menudataList;
}
由于這里用到的@Data等注解,該注解是引用lombok中,所以需要在pom.xml文件中添加依賴。
<!--添加@Data注解依賴-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.6</version>
</dependency>
創(chuàng)建Menudatas類,作為子集(xml文件第二層<mpmenu>,即<root>下面的<mpmenu>的<mpmenu>)。

源碼:
package com.example.business.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.xml.bind.annotation.*;
@Data //注在類上,提供類的get、set、equals、hashCode、canEqual、toString方法,需配置lombok依賴
@AllArgsConstructor //注在類上,提供類的全參構(gòu)造
@NoArgsConstructor //注在類上,提供類的無(wú)參構(gòu)造
@XmlRootElement(name = "mpmenu")
@XmlAccessorType(XmlAccessType.FIELD)
public class Menudatas {
@XmlAttribute(name = "id")
private String id;
@XmlAttribute(name = "title")
private String title;
@XmlAttribute(name = "image")
private String image;
@XmlAttribute(name = "funcId")
private String funcid;
@XmlAttribute(name = "url")
private String url;
}
注意父集子集的邏輯調(diào)用,如果你的配置文件只有一層關(guān)系,則你不再需要?jiǎng)?chuàng)建Menudatas。
創(chuàng)建MenudataList類,用于返回集合數(shù)據(jù)。

源碼:
package com.example.business.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@Data //注在類上,提供類的get、set、equals、hashCode、canEqual、toString方法
@AllArgsConstructor //注在類上,提供類的全參構(gòu)造
@NoArgsConstructor //注在類上,提供類的無(wú)參構(gòu)造
@XmlRootElement(name = "root")// xml 文件的根元素
@XmlAccessorType(XmlAccessType.FIELD) // 控制默認(rèn)情況下是否對(duì)字段或 Javabean 屬性進(jìn)行系列化。
public class MenudataList {
@XmlElement(name = "mpmenu")
private List<Menudata> menudataList;
public List<Menudata> getMenudataList() {
return menudataList;
}
public void setMenudataList(List<Menudata> menudataList) {
this.menudataList = menudataList;
}
}
3、創(chuàng)建一個(gè)XML解析工具類

源碼:
package com.example.business.util;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.Reader;
import java.io.StringReader;
public class XmlBuilder {
/**
* 將XML轉(zhuǎn)為指定的POJO對(duì)象
*
* @param clazz 需要轉(zhuǎn)換的類
* @param xmlStr xml數(shù)據(jù)
* @return
*/
public static Object xmlStrToObject(Class<?> clazz, String xmlStr) throws Exception {
Object xmlObject = null;
Reader reader = null;
//利用JAXBContext將類轉(zhuǎn)為一個(gè)實(shí)例
JAXBContext context = JAXBContext.newInstance(clazz);
//XMl 轉(zhuǎn)為對(duì)象的接口
Unmarshaller unmarshaller = context.createUnmarshaller();
reader = new StringReader(xmlStr);
xmlObject = unmarshaller.unmarshal(reader);
if (reader != null) {
reader.close();
}
return xmlObject;
}
}
4、創(chuàng)建service接口和service實(shí)現(xiàn)類
service接口:

源碼:
package com.example.business.service;
import com.example.business.bean.Menudata;
import java.util.List;
/**
* 導(dǎo)航欄菜單數(shù)據(jù)
*/
public interface MenudataService {
List<Menudata> listMenu() throws Exception;
}
service實(shí)現(xiàn)類:

源碼:
package com.example.business.serviceImpl;
import com.example.business.bean.Menudata;
import com.example.business.bean.MenudataList;
import com.example.business.service.MenudataService;
import com.example.business.util.XmlBuilder;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
@Service
public class MenudataServiceImpl implements MenudataService {
@Override
public List<Menudata> listMenu() throws Exception {
//讀取Resource目錄下的XML文件
Resource resource = new ClassPathResource("menudata.xml");
//利用輸入流獲取XML文件內(nèi)容
BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream(), "gb2312"));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
buffer.append(line);
}
br.close();
//XML轉(zhuǎn)為JAVA對(duì)象
MenudataList menudataList = (MenudataList) XmlBuilder.xmlStrToObject(MenudataList.class, buffer.toString());
return menudataList.getMenudataList();
}
}
5、創(chuàng)建Controller調(diào)用對(duì)應(yīng)的方法執(zhí)行獲取

源碼:
package com.example.business.controller;
import com.example.business.bean.Menudata;
import com.example.business.service.MenudataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class LoginController {
//將Service注入Web層
@Autowired
MenudataService menudataService;
@RequestMapping("toLogin")
public String toLogin(){
return "list";
}
@ResponseBody
@RequestMapping("findMenuData")
public List<Menudata> findMenuData() throws Exception {
List<Menudata> str = menudataService.listMenu();
return str;
}
}
HTML:(使用Layui框架,插件自行去官網(wǎng)下載)

HTML頁(yè)面代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<link rel="stylesheet" href="layui/css/layui.css" rel="external nofollow" type="text/css"></link>
<link rel="stylesheet" href="css/admin.css" rel="external nofollow" >
<style type="text/css">
.welcome {
margin: auto;
width: 400px;
height: 350px;
background: url("image/logos.png") no-repeat center center;
background-size: cover;
}
.modal {
display: none;
padding: 20px;
}
</style>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
<div class="layui-header custom-header">
<!--左側(cè)導(dǎo)航欄收展按鈕-->
<ul class="layui-nav layui-layout-left">
<li class="layui-nav-item slide-sidebar" lay-unselect>
<a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="icon-font"><i class="ai ai-menufold"></i></a>
</li>
</ul>
<!--右側(cè)導(dǎo)航欄狀態(tài)按鈕-->
<ul class="layui-nav layui-layout-right">
<li class="layui-nav-item">
<a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
<img src="http://t.cn/RCzsdCq" class="layui-nav-img">
賢心
</a>
<dl class="layui-nav-child">
<dd><a href="">基本資料</a></dd>
<dd><a href="">安全設(shè)置</a></dd>
</dl>
</li>
<li class="layui-nav-item"><a href="">注銷</a></li>
</ul>
</div>
<div class="layui-side custom-admin" id="menudata">
<div class="layui-side-scroll">
<div class="custom-logo">
<img src="image/logo.png" alt=""/>
<h1>后臺(tái)管理系統(tǒng)</h1>
</div>
<ul id="Nav" class="layui-nav layui-nav-tree layui-inline" lay-filter="demo">
</ul>
</div>
</div>
<!-- 嵌套層內(nèi)容 -->
<div class="layui-body" style="height: 95%;">
<div class="layui-tab app-container" lay-allowClose="true" lay-filter="tabs">
<ul id="appTabs" class="layui-tab-title custom-tab"></ul>
<div class="layui-tab-content">
<div id="welcome" style="width:100%;height:100%;display:flex;">
<div class="welcome"></div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="layui/layui.js"></script>
<script type="text/javascript" src="layui/layui.all.js"></script>
<script src="/js/home.js"></script>
<script type="text/javascript">
//頁(yè)面加載事件
window.onload = function () {
getMenuData();
};
//獲取導(dǎo)航欄菜單
function getMenuData() {
$.ajax({
type: "GET",
url: "findMenuData",
cache: false,
success: function (data) {
//將layui在頁(yè)面加載時(shí)渲染出來(lái)的span.layui-nav-bar利用DOM先刪除掉再重新渲染
$('#nav').find('span.layui-nav-bar').remove();
//console.log(data);
//遍歷map集合
$.each(data, function (i) {
var menu = '<li class="layui-nav-item">' + '<a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" >' + '<i class="layui-icon layui-icon-friends"></i>' + '<em>' + data[i].title + '</em>' + '</a>';
if (data[i].menudataList) {
var menus = '';
$.each(data[i].menudataList, function (j) {
menus = menus + '<dl class="layui-nav-child">' + '<dd><a href="">' + data[i].menudataList[j].title + '</a></dd>' + '</dl>';
})
menu = menu + menus;
}
menu = menu + '</li>';
//console.log(menu)
$("#menudata ul").append(menu);
});
xuanran();
}
});
}
//重新渲染
function xuanran() {
layui.use('element', function () {
var element = layui.element;
var layFilter = $("#nav").attr('lay-filter');
element.render('nav', layFilter);
})
}
</script>
</body>
</html>
運(yùn)行效果:

總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
MybatisPlus實(shí)現(xiàn)簡(jiǎn)單增刪改查功能
這篇文章主要介紹了MybatisPlus實(shí)現(xiàn)簡(jiǎn)單增刪改查的相關(guān)資料,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04
java靜態(tài)工具類注入service出現(xiàn)NullPointerException異常處理
如果我們要在我們自己封裝的Utils工具類中或者非controller普通類中使用@Autowired注解注入Service或者M(jìn)apper接口,直接注入是報(bào)錯(cuò)的,因Utils用了靜態(tài)方法,我們無(wú)法直接用非靜態(tài)接口的,遇到這問(wèn)題,我們要想法解決,下面小編就簡(jiǎn)單介紹解決辦法,需要的朋友可參考下2021-09-09
spring boot國(guó)際化之MessageSource的使用方法
這篇文章主要給大家介紹了spring boot國(guó)際化之MessageSource使用的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
阿里云部署SpringBoot項(xiàng)目啟動(dòng)后被殺進(jìn)程的問(wèn)題解析
這篇文章主要介紹了阿里云部署SpringBoot項(xiàng)目啟動(dòng)后被殺進(jìn)程的問(wèn)題,本文給大家分享問(wèn)題原因所在及解決步驟,需要的朋友可以參考下2023-09-09
Java8中方便又實(shí)用的Map函數(shù)總結(jié)
java8之后,常用的Map接口中添加了一些非常實(shí)用的函數(shù),可以大大簡(jiǎn)化一些特定場(chǎng)景的代碼編寫,提升代碼可讀性,快跟隨小編一起來(lái)看看吧2022-11-11

