Python實戰社羣php
Java實戰社羣前端
長按識別下方二維碼,按需求添加java
掃碼關注添加客服git
進Python社羣▲程序員
掃碼關注添加客服web
進Java社羣▲spring
做者丨不同的科技宅 c#
來源:後端
https://juejin.im/post/6844904083942277127#heading-36微信
前言
創建一個全新的項目,或者把舊的龐大的項目,進行拆分紅多個項目。在創建新的項目中,常常須要作一些重複的工做,好比說拷貝一下經常使用的工具類,通用代碼等等。因此就能夠作一個基礎的項目方便使用,在經歷新項目的時候,直接在基礎項目上進行簡單配置就能夠開發業務代碼了。
基礎項目該包含哪些東西。
Swagger在線接口文檔。
CodeGenerator 代碼生成器。
統一返回。
通用的分頁對象。
經常使用工具類。
全局異常攔截。
錯誤枚舉。
自定義異常。
多環境配置文件。
Maven多環境配置。
日誌配置。
JenkinsFile。
能夠在評論區進行補充,我把 Spring Boot 相關的文章整理成了 PDF,關注 Java後端,後臺回覆 666 下載這本 Java技術棧手冊。
Swagger
寫接口文檔一般是一件比較頭疼的事情,然而swagger就用是用來幫咱們解決這個問題的。能夠在線生成接口文檔,而且能夠在頁面上進行測試。

能夠很是清楚的顯示,請求數據已經響應數據。固然這一切都須要在代碼中進行配置。

經常使用的Swagger註解
@Api用於Controller
@ApiOperation用於Controller內的方法。
@ApiResponses用於標識接口返回數據的類型。
@ApiModel用於標識類的名稱
@ApiModelProperty用於標識屬性的名稱
案例
@RestController @Api(tags = "用戶") @AllArgsConstructor @RequestMapping("/user") public class UserController { private IUserService userService; @ApiOperation("獲取用戶列表") @GetMapping("/listUser") @ApiResponses( @ApiResponse(code = 200, message = "操做成功", response = UserVo.class) ) public ResultVo listUser(@Validated ListUserForm listUserForm){ return ResultVoUtil.success(userService.listUser(listUserForm)); } }
@Data @ApiModel("獲取用戶列表須要的表單數據") @EqualsAndHashCode(callSuper = false) public class ListUserForm extends PageForm<ListUserForm> { @ApiModelProperty("用戶狀態") @NotEmpty(message = "用戶狀態不能爲空") @Range(min = -1 , max = 1 , message = "用戶狀態有誤") private String status; }
對應的swagger的配置能夠查看基礎項目內的SwaggerConfiguration.java
.
CodeGenerator代碼生成器。
mybatis_plus代碼生成器能夠幫咱們生成
entity
,service
,serviceImpl
,mapper
,mapper.xml
。省去了創建一大堆實體類的麻煩。
因爲配置太長這裏就不貼出來了,對應的CodeGenerator的配置能夠查看基礎項目內的CodeGenerator.java
.
經常使用的封裝
統一返回 ResultVo
將全部的接口的響應數據的格式進行統一。
@Data @ApiModel("固定返回格式") public class ResultVo { @ApiModelProperty("錯誤碼") private Integer code; @ApiModelProperty("提示信息") private String message; @ApiModelProperty("響應數據") private Object data; }
抽象表單 BaseForm
public abstract class BaseForm<T> { public abstract T buildEntity(); }
有小夥伴可能有疑問了,這個類有啥用呢。先看一下,下面的代碼。
@Override public boolean addUser(AddUserForm userForm) { User user = new User(); user.setNickname(userForm.getNickname()); user.setBirthday(userForm.getBirthday()); user.setUsername(userForm.getUsername()); user.setPassword(userForm.getPassword()); return save(user); }
重構一下,感受清爽了一些。
@Override public boolean addUser(AddUserForm userForm) { User user = new User(); BeanUtils.copyProperties(this,user); return save(user); }
使用BaseForm進行重構 AddUserForm 繼承 BaseForm並重寫buildEntity
@Data @EqualsAndHashCode(callSuper = false) public class AddUserForm extends BaseForm<User> { private String nickname; private Date birthday; private String username; private String password; @Override public User buildEntity() { User user = new User(); BeanUtils.copyProperties(this,user); return user; } }
@Override public boolean addUser(AddUserForm userForm) { return save(userForm.buildEntity()); }
上面的代碼有沒有種似曾相識的感受,不少狀況都是將接受到的參數,轉變成對應的實體類而後保存或者更新。因此對於這類的form
能夠繼承baseform
並實現buildEntity()
這樣能夠更加符合面向對象,service
不須要關心form
如何轉變成entity
,只須要在使用的時候調用buildEntity()
便可,尤爲是在form
-> entity
相對複雜的時候,這樣作能夠減小service
內的代碼。讓代碼邏輯看起來更加清晰。
通用的分頁對象
涉及到查詢的時候,絕大多數都須要用到分頁,因此說封裝分頁對象就頗有必要。能夠注意下 PageForm.calcCurrent()
、PageVo.setCurrentAndSize()
、PageVo.setTotal()
這個幾個方法。
PageForm
@Data @ApiModel(value = "分頁數據", description = "分頁須要的表單數據") public class PageForm<T extends PageForm<?>>{ @ApiModelProperty(value = "頁碼 從第一頁開始 1") @Min(value = 1, message = "頁碼輸入有誤") private Integer current; @ApiModelProperty(value = "每頁顯示的數量 範圍在1~100") @Range(min = 1, max = 100, message = "每頁顯示的數量輸入有誤") private Integer size; @ApiModelProperty(hidden = true) public T calcCurrent(){ current = (current - 1 ) * size; return (T) this; } }
PageVo @Data public class PageVo<T> { @ApiModelProperty(value = "分頁數據") private List<T> records; @ApiModelProperty(value = "總條數") private Integer total; @ApiModelProperty(value = "總頁數") private Integer pages; @ApiModelProperty(value = "當前頁") private Integer current; @ApiModelProperty(value = "查詢數量") private Integer size; @ApiModelProperty(hidden = true) public PageVo<T> setCurrentAndSize(PageForm<?> pageForm){ BeanUtils.copyProperties(pageForm,this); return this; } @ApiModelProperty(hidden = true) public void setTotal(Integer total) { this.total = total; this.setPages(this.total % this.size > 0 ? this.total / this.size + 1 : this.total / this.size); } }案例
ListUserForm
@Data @ApiModel("獲取用戶列表須要的表單數據") @EqualsAndHashCode(callSuper = false) public class ListUserForm extends PageForm<ListUserForm> { @ApiModelProperty("用戶狀態") @NotEmpty(message = "用戶狀態不能爲空") @Range(min = -1 , max = 1 , message = "用戶狀態有誤") private String status; }
UserServiceImpl
@Override public PageVo<UserVo> listUser(ListUserForm listUserForm) { PageVo<UserVo> pageVo = new PageVo<UserVo>().setCurrentAndSize(listUserForm); pageVo.setTotal(countUser(listUserForm.getStatus())); pageVo.setRecords(userMapper.listUser(listUserForm.calcCurrent())); return pageVo; } private Integer countUser(String status){ return count(new QueryWrapper<User>().eq("status",status)); }
UserController
@ApiOperation("獲取用戶列表") @GetMapping("/listUser") @ApiResponses( @ApiResponse(code = 200, message = "操做成功", response = UserVo.class) ) public ResultVo listUser(@Validated ListUserForm listUserForm){ return ResultVoUtil.success(userService.listUser(listUserForm)); }

注意的點
PageVo在實例化的時候須要設置當前頁和每頁顯示的數量 能夠調用
setCurrentAndSize()
完成。進行分頁查詢的時候,須要計算偏移量。
listUserForm.calcCurrent()
爲何要計算偏移量呢?
假如查詢第1頁每頁顯示10條記錄,前端傳遞過來的參數是
current=1&&size=10
,這個時候limit 1,10
沒有問題。假如查詢第2頁每頁顯示10條記錄,前端傳遞過來的參數是
current=2&&size=10
,這個時候limit 2,10
就有問題,實際應該是limit 10,10
。calcCurrent()的做用就是如此
。
爲何不用MybatisPlus自帶的分頁插件呢?
自帶的分頁查詢在大量數據下,會出現性能問題。
經常使用工具類
經常使用工具類能夠根據本身的開發習慣引入。
異常處理
異常處理的大體流程主要以下。
異常信息拋出 ->
ControllerAdvice
進行捕獲格式化輸出內容手動拋出
CustomException
並傳入ReulstEnum
——> 進行捕獲錯誤信息輸出錯誤信息。
自定義異常
@Data @EqualsAndHashCode(callSuper = false) public class CustomException extends RuntimeException { private final Integer code; private final String method; public CustomException(ResultEnum resultEnum, String method) { super(resultEnum.getMsg()); this.code = resultEnum.getCode(); this.method = method; } public CustomException(Integer code, String message, String method) { super(message); this.code = code; this.method = method; } }
錯誤信息枚舉
根據業務進行添加。
@Getter public enum ResultEnum { UNKNOWN_EXCEPTION(100, "未知異常"), ADD_ERROR(103, "添加失敗"), UPDATE_ERROR(104, "更新失敗"), DELETE_ERROR(105, "刪除失敗"), GET_ERROR(106, "查找失敗"), ; private Integer code; private String msg; ResultEnum(Integer code, String msg) { this.code = code; this.msg = msg; } public static ResultEnum getByCode(int code){ for (ResultEnum resultEnum : ResultEnum.values()) { if(code == resultEnum.getCode()){ return resultEnum; } } return null; } }
全局異常攔截
全局異常攔截是使用@ControllerAdvice
進行實現,經常使用的異常攔截配置能夠查看 GlobalExceptionHandling。
@Slf4j @RestControllerAdvice public class GlobalExceptionHandling { @ExceptionHandler(value = CustomException.class) public ResultVo processException(CustomException e) { log.error("位置:{} -> 錯誤信息:{}", e.getMethod() ,e.getLocalizedMessage()); return ResultVoUtil.error(Objects.requireNonNull(ResultEnum.getByCode(e.getCode()))); } @ResponseStatus(HttpStatus.OK) @ExceptionHandler(Exception.class) public ResultVo exception(Exception e) { e.printStackTrace(); return ResultVoUtil.error(ResultEnum.UNKNOWN_EXCEPTION); } }
案例
Controller
@ApiOperation("刪除用戶") @DeleteMapping("/deleteUser/{id}") public ResultVo deleteUser(@PathVariable("id") String id){ userService.deleteUser(id); return ResultVoUtil.success(); }
Service
@Override public void deleteUser(String id) { if(!removeById(id)){ throw new CustomException(ResultEnum.DELETE_ERROR, MethodUtil.getLineInfo()); } }
結果


將報錯代碼所在的文件第多少行都打印出來。方便排查。
注意的點
全部手動拋出的錯誤信息,都應在錯誤信息枚舉ResultEnum
進行統一維護。不一樣的業務使用不一樣的錯誤碼。方便在報錯時進行分辨。快速定位問題。
多環境配置
SpringBoot多環境配置
對於一個項目來說基本都4有個環境dev
,test
,pre
,prod
,對於SpringBoot項目多創建幾個配置文件就能夠了。而後啓動的時候能夠經過配置spring.profiles.active
來選擇啓動的環境。

java -jar BasicProject.jar --spring.profiles.active=prod
Maven多環境配置
假如想在打包的時候動態指定環境,這個時候就須要藉助Maven的xml來實現。
配置XML
<profiles> <profile> <id>dev</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <activatedProperties>dev</activatedProperties> </properties> </profile> <profile> <id>test</id> <properties> <activatedProperties>test</activatedProperties> </properties> </profile> <profile> <id>pre</id> <properties> <activatedProperties>pre</activatedProperties> </properties> </profile> <profile> <id>prod</id> <properties> <activatedProperties>prod</activatedProperties> </properties> </profile> </profiles>
更改application.yml
spring: profiles: # 選擇環境 active: @activatedProperties@
使用案例
mvn clean package -P prod mvn clean package -P pre mvn clean package -P test
打包完能夠解壓開查看application.yml
會發現spring.profiles.active=@activatedProperties@
發生了改變。
日誌配置
採用logback日誌配置
JenkinsFile
JenkinsFile確定顧名思義是給jenkins用的。主要是配置項目根據如何進行構建併發布到不一樣的環境。須要去了解pipeline語法,以及如何配置jenkins。
JenkinsFileDemo https://gitee.com/huangxunhui/basic_project/blob/master/Jenkinsfile
代碼地址
https://gitee.com/huangxunhui/basic_project.git
程序員專欄 掃碼關注填加客服 長按識別下方二維碼進羣
近期精彩內容推薦:
在看點這裏好文分享給更多人↓↓