Springboot-Thymeleaf-Customer-File
接口要寫(xiě)嚴(yán)格竖哩,一個(gè)接口一個(gè)用途该抒。
這樣別人調(diào)用接口時(shí)懂算,不會(huì)有任何誤會(huì)窿祥。
前言
之前的程序:
之前用springboot+thymeleaf做了前后端實(shí)現(xiàn)的用戶的增刪改查株憾,現(xiàn)在要加個(gè)單文件上傳、多文件上傳與下載晒衩,并且優(yōu)化頁(yè)面嗤瞎。前面三大操作都是借助了項(xiàng)目提供的接口。我在自己的服務(wù)器上啟動(dòng)一個(gè)程序听系,通過(guò)調(diào)用它提供的接口贝奇,在項(xiàng)目服務(wù)器上實(shí)現(xiàn)三大功能,并且把相應(yīng)的信息發(fā)送至Mysql靠胜,并實(shí)現(xiàn)可視化掉瞳。
由于我的程序是對(duì)應(yīng)了項(xiàng)目毕源,所以有些地方具有特殊性。
先看頁(yè)面
用戶目錄
list.html
<!DOCTYPEhtml>
<htmllang="en"xmlns:th="http://www.thymeleaf.org">
<head>
<metacharset="UTF-8"/>
<title>客戶列表</title>
<style>
table{border-collapse:collapse;}
table,th,td{border:1pxsolidblack;padding:5px;text-align:center;}
</style>
<linkrel="stylesheet"th:href="@{/css/bootstrap.css}"/>
</head>
<bodyclass="container">
<br/>
<br/>
<ath:href="edit">新增用戶</a>
<br/>
<br/>
<table>
<thead>
<thwidth="12.5%">id</th>
<thwidth="12.5%">name</th>
<thwidth="12.5%">age</th>
<thwidth="12.5%">used</th>
<thwidth="50%">操作</th>
</thead>
<tbody>
<trth:each="customer : ${customers}">
<tdth:text="${customer.id}"></td>
<tdth:text="${customer.name}"></td>
<tdth:text="${customer.age}"></td>
<tdth:text="${customer.used}"></td>
<td>
<ath:href="@{/customers/edit(id=${customer.id})}">編輯</a>
<ath:href="@{/customers/goingToDel(pageNum=${pageNum},id=${customer.id})}">刪除</a>
<ath:href="@{/customers/file(customerId=${customer.id})}">單文件上傳</a>
<ath:href="@{/customers/multiple(customerId=${customer.id})}">多文件上傳</a>
<ath:href="@{/customers/goToFileSystem(customerId=${customer.id})}">我的文件</a>
</td>
</tr>
</tbody>
</table>
<divth:text="當(dāng)前頁(yè)數(shù)"></div>
<divth:text="${pageNum}"></div>
<divclass="modal-footer no-margin-top">
<ulclass="pagination pull-right no-margin">
<!--首頁(yè)-->
<li>
<ath:href="'/customers/list?pageNum=0'">首頁(yè)</a>
</li>
<!--上一頁(yè)-->
<lith:if="${customers.hasPrevious()}">
<ath:href="'/customers/list?pageNum=' + ${customers.previousPageable().getPageNumber()}"th:text="上一頁(yè)"></a>
</li>
<!--中間頁(yè)-->
<lith:each="pageNum:${#numbers.sequence(0, customers.getTotalPages()-1)}">
<ath:href="'/customers/list?pageNum=' + ${pageNum}"th:text="${pageNum + 1}"th:style="'font-weight:bold;background: #6faed9;'"></a>
</li>
<!--下一頁(yè)-->
<lith:if="${customers.hasNext()}">
<ath:href="'/customers/list?pageNum=' + ${customers.nextPageable().getPageNumber()}"th:text="下一頁(yè)"></a>
</li>
<!--尾頁(yè)-->
<li>
<ath:href="'/customers/list?pageNum=' + ${customers.getTotalPages() - 1}">尾頁(yè)</a>
</li>
</ul>
</div>
</body>
</html>
單文件上傳
file.html
<!DOCTYPEhtml>
<htmlxmlns="http://www.w3.org/1999/xhtml"xmlns:th="http://www.thymeleaf.org"xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<metacharset="UTF-8"/>
<title>Inserttitlehere</title>
</head>
<body>
<h1th:inlines="text">文件上傳</h1>
<formth:action="@{/customers/singleFile(customerId=${customerId})}"method="post"enctype="multipart/form-data">
<p>選擇文件:<inputtype="file"name="file"/></p>
<p><inputtype="submit"value="上傳"/></p>
<p><inputtype="button"value="返回"onclick="JavaScript:history.go(-1)"/></p>
</form>
</body>
</html>
文件列表
fielList.html
<!DOCTYPEhtml>
<htmllang="en"xmlns:th="http://www.thymeleaf.org">
<head>
<metacharset="UTF-8"/>
<title>客戶文件列表</title>
<style>
table{border-collapse:collapse;}
table,th,td{border:1pxsolidblack;padding:5px;text-align:center;}
</style>
<linkrel="stylesheet"th:href="@{/css/bootstrap.css}"/>
<scripttype="text/javascript">
functionconfirmDel(fileId,customerId)
? ? ?? {
if(window.confirm("您確定要?jiǎng)h除該條數(shù)據(jù)嗎陕习?")){
document.location="/customers/delFile?fileId="+fileId+"&customerId="+customerId
? ? ? ? ?? }
? ? ?? }
</script>
</head>
<bodyclass="container">
<table>
<thead>
<thwidth="20%">線上文件Id</th>
<thwidth="20%">線上文件用戶Id</th>
<thwidth="20%">線上文件名</th>
<thwidth="20%">線上文件地址</th>
<thwidth="20%">操作</th>
</thead>
<tbody>
<trth:each="file : ${files}">
<tdth:text="${file.fileId}"></td>:
<tdth:text="${file.customerId}"></td>
<tdth:text="${file.fileName}"></td>
<tdth:text="${file.fullPath}"></td>
<td>
<ath:href="@{/customers/download(fullPath=${file.fullPath},fileName=${file.fileName})}">下載</a>
<ahref="javascript:void(0)"th:onclick="|confirmDel( ${file.fileId} ,${file.customerId}) |">刪除</a>
</td>
</tr>
</tbody>
<div>
<inputtype="button"value="返回"onclick="JavaScript:history.go(-1)"/>
</div>
</table>
</body>
</html>
下載文件
TestController中的一部分
@GetMapping(value="download")
publicResponseEntity<byte[]>download(@RequestParam("fullPath")StringfilePath,@RequestParam("fileName")StringfileName)throwsUnsupportedEncodingException{
Stringauthorization="Bearer ...";
byte[]res=feignService.downLoadFile(filePath,authorization);
ResponseEntity<byte[]>entity=newResponseEntity<byte[]>(HttpStatus.OK);
HttpHeadersheaders=newHttpHeaders();
headers.add("Content-Type","application/octet-stream");
headers.add("Connection","close");
headers.add("Accept-Ranges","bytes");
headers.add("Content-Disposition",
"attachment;filename="+newString(fileName.getBytes("GB2312"),"ISO8859-1"));
entity=newResponseEntity<byte[]>(res,headers,HttpStatus.OK);
returnentity;
}
刪除文件彈窗
<scripttype="text/javascript">
functionconfirmDel(fileId,customerId)
?? {
if(window.confirm("您確定要?jiǎng)h除該條數(shù)據(jù)嗎霎褐?")){
document.location="/customers/delFile?fileId="+fileId+"&customerId="+customerId
? ? ?? }
?? }
</script>
<ahref="javascript:void(0)"th:onclick="|confirmDel( ${file.fileId} ,${file.customerId}) |">刪除</a>
多文件上傳
multiple.html
<!DOCTYPEhtml>
<htmlxmlns="http://www.w3.org/1999/xhtml"xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<metacharset="UTF-8"/>
<title>Inserttitlehere</title>
</head>
<body>
<h1th:inlines="text">文件上傳</h1>
<formth:action="@{/customers/multiFiles(customerId=${customerId})}"method="post"enctype="multipart/form-data">
<p>選擇文件1:<inputtype="file"name="files"/></p>
<p>選擇文件2:<inputtype="file"name="files"/></p>
<p>選擇文件3:<inputtype="file"name="files"/></p>
<p>選擇文件4:<inputtype="file"name="files"/></p>
<p>選擇文件5:<inputtype="file"name="files"/></p>
<p><inputtype="submit"value="上傳"/></p>
<p><inputtype="button"value="返回"onclick="JavaScript:history.go(-1)"/></p>
</form>
</body>
</html>
選擇任意數(shù)量的不同的或相同的文件
這里有點(diǎn)復(fù)雜,之后講
上傳至不同用戶管轄的文件列表
點(diǎn)擊"我的文件"直達(dá)文件系統(tǒng)
若該用戶沒(méi)有所屬的文件该镣,則顯示空
接口文檔閱讀
作為小白冻璃,我之前沒(méi)有讀過(guò)接口文檔說(shuō)明。不同公司的接口文檔不一樣损合。
我這里使用了之前學(xué)習(xí)的Feign來(lái)調(diào)用這些接口俱饿,非常方便。
接口調(diào)用
不管是誰(shuí)給的接口塌忽,只要我們要用拍埠,就要先postman調(diào)用,試試水土居。如果自己程序?qū)懞昧嗽婀海l(fā)現(xiàn)接口有問(wèn)題導(dǎo)致delay,血虧擦耀。
隨便舉個(gè)例子
這些接口都會(huì)返回string字符串棉圈,我所要的文件線上地址以及錯(cuò)誤碼都需要我自己提取。
文件結(jié)構(gòu)
程序里待調(diào)用的接口
packagecom.mybatis_druid_mysql.demo.Service;
importcom.mybatis_druid_mysql.demo.Entity.File;
importorg.springframework.cloud.openfeign.FeignClient;
importorg.springframework.stereotype.Service;
importorg.springframework.web.bind.annotation.*;
importorg.springframework.web.multipart.MultipartFile;
importjava.util.List;
@FeignClient(name="jerryNiu",url="http://product360-newproduct-dev.kg.plantdata.cn/")
publicinterfaceFeignService{
@PostMapping(value="api/kgms/file",consumes="multipart/form-data")
StringupLoadFile(@RequestPart(value="file")MultipartFilefile,@RequestHeader(value="authorization")Stringauthorization);
@PostMapping(value="api/kgms/file/multi",consumes="multipart/form-data")
StringupLoadMultiFile(@RequestPart(value="files")List<MultipartFile>files,@RequestHeader(value="authorization")Stringauthorization);
@GetMapping(value="api/kgms/file/download")
byte[]downLoadFile(@RequestParam(value="filePath")StringfilePath,@RequestHeader(value="authorization")Stringauthorization);
}
RequestPart:
Annotation that can be used to associate the part of a "multipart/form-data" request with a method argument.
RequestHeader:
Annotation which indicates that a method parameter should be bound to a web request header
啟動(dòng)類
package com.mybatis_druid_mysql.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
public class DemoApplication {
public static void main(String[] args){
SpringApplication.run(DemoApplication.class,args);
}
}
EnableFeignClients:
Scans for interfaces that declare they are feign clients (via FeignClient @FeignClient). Configures component scanning directives for use with org.springframework.context.annotation.Configuration @Configuration classes.
MapperScan:
Use this annotation to register MyBatis mapper interfaces when using Java Config. It performs when same work as MapperScannerConfigurer via MapperScannerRegistrar.
至于其他倆注解就不介紹了眷蜓。
Controller
package com.mybatis_druid_mysql.demo.Controller;
import com.mybatis_druid_mysql.demo.Entity.Customer;
import com.mybatis_druid_mysql.demo.Entity.File;
import com.mybatis_druid_mysql.demo.Service.FeignService;
import com.mybatis_druid_mysql.demo.Service.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServlet;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@org.springframework.stereotype.Controller
@RequestMapping("customers")
@Slf4j
public class TestController extends HttpServlet {
@Autowired
private Service service;
@Autowired
private FeignService feignService;
...
}
單文件上傳
TestController里的一部分
@RequestMapping("file")
public String file(ModelMap map, @RequestParam(value = "customerId") Integer customerId){
map.addAttribute("customerId",customerId);
return "customer/file";
}
@PostMapping(value = "singleFile" ,consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public String fileUpload(ModelMap map,
MultipartFile file,
@RequestParam(value = "customerId") Integer customerId){
String authorization = "Bearer ...";
File file1 = new File();
file1.setCustomerId(customerId);
file1.setFileName(file.getOriginalFilename());
System.out.println("Hello World");
System.out.println(file.getOriginalFilename());
System.out.println(file.getContentType());
file1.setFullPath(feignService.upLoadFile(file,authorization).substring(35,87));
System.out.println(file1);
if(file1.getFileId()==null){
file1.setFileId(0);
}
else {
file1.setFileId(file1.getFileId()+1);
}
System.out.println(file1);
List file2 = service.getAllFiles();
System.out.println(file2);
System.out.println(feignService.upLoadFile(file,authorization).substring(35,87));
System.out.println(feignService.upLoadFile(file, authorization).substring(11,14));
System.out.println(feignService.upLoadFile(file,authorization));
log.error(feignService.upLoadFile(file,authorization));
if(feignService.upLoadFile(file, authorization).substring(11,14).equals("200")){
service.insertOneFile(file1);
List file3 = service.getAllFiles();
map.addAttribute("files",file3);
return "redirect:/customers/fileList?customerId="+customerId;
}
map.addAttribute("files",file2);
return "redirect:/customers/fileList?customerId="+customerId;
}
ModelMap是向頁(yè)面?zhèn)鲾?shù)據(jù)的工具分瘾。
給Mysql傳數(shù)據(jù)時(shí),不用手動(dòng)設(shè)置id吁系,只要在Mysql中設(shè)置id為自增主鍵德召,他會(huì)自己配置。
MultiPartFile:
A representation of an uploaded file received in a multipart request.The file contents are either stored in memory or temporarily on disk. In either case, the user is responsible for copying file contents to a session-level or persistent store as and if desired. The temporary storage will be cleared at the end of request processing.
要看程序中各項(xiàng)數(shù)據(jù)的值汽纤,最好用log.info上岗,而不是像這里用的sout。
文件下載
@GetMapping(value = "download")
public ResponseEntity download(@RequestParam("fullPath") String filePath,@RequestParam("fileName") String fileName) throws UnsupportedEncodingException {
String authorization = "Bearer ...";
byte[] res = feignService.downLoadFile(filePath,authorization);
ResponseEntity entity = new ResponseEntity(HttpStatus.OK);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/octet-stream");
headers.add("Connection", "close");
headers.add("Accept-Ranges", "bytes");
headers.add("Content-Disposition",
"attachment;filename=" + new String(fileName.getBytes("GB2312"), "ISO8859-1"));//獲取文件名
entity = new ResponseEntity(res, headers, HttpStatus.OK);
return entity;
}
ResponseEntity:
Extension of HttpEntity that adds a HttpStatus status code. Used in RestTemplate as well
HttpEntity :
Represents an HTTP request or response entity, consisting of headers and body.
這里的Headers與postman上寫(xiě)的headers如出一轍蕴坪。
代碼效果一開(kāi)始就展示過(guò)了肴掷。
多文件上傳
/*
* 獲取multifile.html頁(yè)面
*/
@RequestMapping("multiple")
public String multifile(ModelMap map, @RequestParam(value = "customerId") Integer customerId){
map.addAttribute("customerId",customerId);
return "customer/multiple";
}
/**
* 實(shí)現(xiàn)多文件上傳
* */
@PostMapping(value="multiFiles",
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public String multifileUpload(ModelMap map,
@RequestPart List files,
@RequestParam(value = "customerId") Integer customerId) throws IOException {
String authorization = "Bearer ...";
if(files.get(0).isEmpty()&&files.get(1).isEmpty()&&files.get(2).isEmpty()&&files.get(3).isEmpty()&&files.get(4).isEmpty()){
return "redirect:/customers/fileList?customerId="+customerId;
}
System.out.println(files.size());
//上傳文件
String result = feignService.upLoadMultiFile(files,authorization);
System.out.println(result);
int num = 0;//計(jì)算總文件數(shù)
List availableFile = new ArrayList<>();//記錄非空的文件index
List filePath = new ArrayList<>();//記錄各個(gè)文件線上地址
//多文件上傳返回值預(yù)處理
String returnMessage;
returnMessage = result
.replaceAll("errCode","")
.replaceAll("message","")
.replaceAll("}","")
.replace('{',':')
.replaceAll(":","")
.replaceAll(":","")
.replaceAll(",","")
.replace("\"", "")
.replaceAll("data","")
.replaceAll("]","")
.replace('[',':')
.replaceAll(":","")
.replaceAll("fullPath","")
.replaceAll("fileName"," : ");
//分析并拆解上傳文件的返回值
for(int i=0 ; i
if(!files.get(i).isEmpty()){
availableFile.add(i);//第i號(hào)文件有東西
num++;
log.info(returnMessage);
int begin = returnMessage.lastIndexOf("/");
int end = returnMessage.lastIndexOf(":");
log.info(returnMessage.substring(begin-17,end-1));
filePath.add(returnMessage.substring(begin-17,end-1));
log.info(returnMessage.replaceAll(returnMessage.substring(begin-17,end-1),""));
returnMessage = returnMessage.replaceAll(returnMessage.substring(begin-17,end-1),"");
log.info(returnMessage.substring(0,returnMessage.lastIndexOf(":")-1));
returnMessage = returnMessage.substring(0,returnMessage.lastIndexOf(":")-1);
}
else {
files.remove(i);
if(i!=0)
i--;//https://it4all.blog.csdn.net/article/details/77915981
}
}
//同步上傳mysql
System.out.println(filePath);
for(int i=0 ; i
File file = new File();
file.setFileName(files.get(availableFile.get(i)).getOriginalFilename());
log.info(files.get(availableFile.get(i)).getOriginalFilename());
file.setFullPath(filePath.get(num-i-1));
file.setFileId(0);
file.setCustomerId(customerId);
service.insertOneFile(file);
}
System.out.println(files.size());
//打印Mysql
List file2 = service.getAllFiles();
map.addAttribute("files",file2);
return "redirect:/customers/fileList?customerId="+customerId;
}
多文件上傳邏輯就復(fù)雜一些。我希望當(dāng)用戶選擇多文件上傳時(shí)背传,最多一次傳5個(gè)文件呆瞻。項(xiàng)目給我的接口的文件數(shù)量遠(yuǎn)大于我要的5。我需要實(shí)現(xiàn)用戶傳的文件數(shù)小于5時(shí)径玖,將空文件刪除痴脾。并且將返回的字符串整理成我需要的線上文件地址。并且同步到Mysql中挺狰。
MultipartFile:
A representation of an uploaded file received in a multipart request.
文件刪除
這里的刪除并不是在項(xiàng)目服務(wù)器上把文件刪除明郭,而是在Mysql表中刪除數(shù)據(jù)。因?yàn)轫?xiàng)目沒(méi)給相應(yīng)的刪除文件的接口丰泊。
@RequestMapping("delFile")
public String delFile(ModelMap map, @RequestParam(value = "fileId") Integer fileId,
@RequestParam(value = "customerId") Integer customerId){
service.deleteFile(fileId);
List file2 = service.getAllFiles();
System.out.println(file2);
map.addAttribute("files",file2);
System.out.println("ok");
return "redirect:/customers/fileList?customerId="+customerId;
}
查看文件
用戶之前都要先上傳文件薯定,才能看到文件列表。現(xiàn)在我希望能直接有個(gè)查看文件列表的接口瞳购。
@GetMapping(value = "fileList")
public String fileList(ModelMap map,
@RequestParam(value = "customerId") Integer customerId){
List file2 = service.getByCustomerId(customerId);
map.addAttribute("files",file2);
return "customer/fileList";
}
Mysql表同步
我這里通過(guò)mybatis里的mapper實(shí)現(xiàn)與mysql的信息交互话侄。
@Insert("insert into files(file_name,full_path,customer_id) values(#{fileName},#{fullPath},#{customerId})")
@Options(useGeneratedKeys = true,keyColumn = "file_id",keyProperty = "fileId")//展示id只有insert時(shí)要
void insertOneFile(File file);
@Select("select * from files where customer_id = #{customerId}")
@Results( value = {? ? ? ? ? ? ? ? //!!!!
@Result(property = "fileId", column = "file_id"),
@Result(property = "fileName", column = "file_name"),
@Result(property = "fullPath", column = "full_path"),
@Result(property = "customerId", column = "customer_id")})
List getByCustomerId(@Param("customerId") int customerId);
@Select("select * from files where file_id = #{fileId}")
@Results( value = {? ? ? ? ? ? ? ? //!!!!
@Result(property = "fileId", column = "file_id"),
@Result(property = "fileName", column = "file_name"),
@Result(property = "fullPath", column = "full_path"),
@Result(property = "customerId", column = "customer_id")})
File getByFileId(@Param("fileId") int fileId);
@Select("select * from files")
@Results( value = {? ? ? ? ? ? ? ? //!!!!
@Result(property = "fileId", column = "file_id"),
@Result(property = "fileName", column = "file_name"),
@Result(property = "fullPath", column = "full_path"),
@Result(property = "customerId", column = "customer_id")})
List getAllFiles();
@Delete("delete from files where file_id = #{fileId}")
void delFile(@Param("fileId") int fileId);
file實(shí)體類(注意!Q年堆!這里的file不是jdk里的file,而是我自己設(shè)置的實(shí)體類U到健1渖ァ!
@Entity(name = "files")
@Data
public class File implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Integer fileId;
private String fileName;
private String fullPath;
private Integer customerId;
}
我在Navicat中把fileId調(diào)成自增主鍵后绢掰,會(huì)出現(xiàn)一個(gè)問(wèn)題:Mysql默認(rèn)主鍵名為id痒蓬,我們?cè)儆肕apper使用Mysql語(yǔ)句時(shí),要將表中的file_id與fileId一一對(duì)應(yīng)滴劲,否則就算在Navicat中看到file_id下的數(shù)據(jù)是存在的攻晒,在select時(shí),會(huì)報(bào)錯(cuò)說(shuō)fileId不能是空班挖。
怎么一一對(duì)應(yīng)呢鲁捏?舉個(gè)例子。
@Delete("delete from files where file_id = #{fileId}")
@Options(useGeneratedKeys = true,keyColumn = "fileId")
@Results( value = {? ? ? ? ? ? ? ? //!!!!
@Result(property = "fileId", column = "file_id"),
@Result(property = "fileName", column = "file_name"),
@Result(property = "fullPath", column = "full_path"),
@Result(property = "customerId", column = "customer_id")})
void delFile(@Param("fileId") int fileId);
produces:它的作用是指定返回值類型萧芙,不但可以設(shè)置返回值類型還可以設(shè)定返回值的字符編碼给梅;
consumes: 指定處理請(qǐng)求的提交內(nèi)容類型(Content-Type),例如application/json, text/html;
enctype 屬性規(guī)定在發(fā)送到服務(wù)器之前應(yīng)該如何對(duì)表單數(shù)據(jù)進(jìn)行編碼双揪。
Service層對(duì)Mapper層的調(diào)用我就不寫(xiě)了破喻。
同步到mysql的數(shù)據(jù)傳輸我使用了druid。
package com.mybatis_druid_mysql.demo.Druid;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
@SpringBootConfiguration
@PropertySource(value = "classpath:/application.properties")
@EnableTransactionManagement
public class Druid {
@Value("${spring.datasource.druid.username}")
private String userName;
@Value("${spring.datasource.druid.password}")
private String password;
@Value("${spring.datasource.druid.driver-class-name}")
private String driverName;
@Value("${spring.datasource.druid.url}")
private String url;
@Value("${spring.datasource.druid.initial-size}")
private int initialSize;
@Value("${spring.datasource.druid.max-active}")
private int maxActive;
@Value("${spring.datasource.druid.min-idle}")
private int minIdle;
@Value("${spring.datasource.druid.max-wait}")
private int maxWait;
@Value("${spring.datasource.druid.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.druid.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize}")
private int maxPoolPreparedStatementPerConnectionSize;
@Bean(name = "datasource")
public DataSource dataSource(){//由druid-spring-boot-starter實(shí)現(xiàn)springboot提供的datasource接口
DruidDataSource dataSource = null;
try{
dataSource = new DruidDataSource();
dataSource.setUsername(userName);
dataSource.setPassword(password);
dataSource.setUrl(url);
dataSource.setDriverClassName(driverName);
dataSource.setInitialSize(initialSize);
dataSource.setMaxActive(maxActive);
dataSource.setMinIdle(minIdle);
dataSource.setMaxWait(maxWait);
dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
}catch (Exception e){
e.printStackTrace();
}
return dataSource;
}
}
這串代碼我在以前的文章大致講過(guò)盟榴。
這樣曹质,就完成了。