一个Spring Boot项目该包含哪些?

开发 后端
建立一个全新的项目,或者把旧的庞大的项目,进行拆分成多个项目。在建立新的项目中,经常需要做一些重复的工作,比如说拷贝一下常用的工具类,通用代码等等。

前言

建立一个全新的项目,或者把旧的庞大的项目,进行拆分成多个项目。在建立新的项目中,经常需要做一些重复的工作,比如说拷贝一下常用的工具类,通用代码等等。

所以就可以做一个基础的项目方便使用,在经历新项目的时候,直接在基础项目上进行简单配置就可以开发业务代码了。

基础项目该包含哪些东西。

  •  Swagger在线接口文档。
  •  CodeGenerator 代码生成器。
  •  统一返回。
  •  通用的分页对象。
  •  常用工具类。
  •  全局异常拦截。
  •  错误枚举。
  •  自定义异常。
  •  多环境配置文件。
  •  Maven多环境配置。
  •  日志配置。
  •  JenkinsFile。   

Swagger

写接口文档通常是一件比较头疼的事情,然而swagger就用是用来帮我们解决这个问题的。可以在线生成接口文档,并且可以在页面上进行测试。

可以非常清楚的显示,请求数据已经响应数据。当然这一切都需要在代码中进行配置。

「注意的点:接口文档只能在测试/开发环境开启,其他环境请关闭。」

常用的Swagger注解

  •  @Api用于Controller
  •  @ApiOperation用于Controller内的方法。
  •  @ApiResponses用于标识接口返回数据的类型。
  •  @ApiModel用于标识类的名称
  •  @ApiModelProperty用于标识属性的名称

案例 

  1. @RestController    
  2. @Api(tags = "用户")    
  3. @AllArgsConstructor    
  4. @RequestMapping("/user")    
  5. public class UserController {    
  6.     private IUserService userService;    
  7.     /**    
  8.      * 获取用户列表    
  9.      * @param listUserForm 表单数据    
  10.      * @return 用户列表    
  11.      */    
  12.     @ApiOperation("获取用户列表")    
  13.     @GetMapping("/listUser")    
  14.     @ApiResponses(    
  15.             @ApiResponse(code = 200message = "操作成功"response = UserVo.class)    
  16.     )    
  17.     public ResultVo listUser(@Validated ListUserForm listUserForm){    
  18.         return ResultVoUtil.success(userService.listUser(listUserForm));    
  19.     }   
  20. }    
  1. @Data    
  2. @ApiModel("获取用户列表需要的表单数据")    
  3. @EqualsAndHashCode(callSuper = false)    
  4. public class ListUserForm extends PageForm<ListUserForm> {     
  5.     /**    
  6.      * 用户状态    
  7.      */    
  8.     @ApiModelProperty("用户状态")    
  9.     @NotEmpty(message = "用户状态不能为空")    
  10.     @Range(min =  -1 , max = 1 , message = "用户状态有误")    
  11.     private String status;    
  12. }   

对应的swagger的配置可以查看基础项目内的SwaggerConfiguration.java.点击这里参考详细教程。关注公众号Java技术栈回复boot可以获取Spring Boot系列教程。

CodeGenerator代码生成器。

mybatis_plus代码生成器可以帮我们生成entity,service,serviceImpl,mapper,mapper.xml。省去了建立一大堆实体类的麻烦。没听过的可以点击这里参考这篇文章。

由于配置太长这里就不贴出来了,对应的CodeGenerator的配置可以查看基础项目内的CodeGenerator.java.

常用的封装

统一返回 ResultVo

将所有的接口的响应数据的格式进行统一。 

  1. @Data    
  2. @ApiModel("固定返回格式")   
  3. public class ResultVo {    
  4.     /**    
  5.      * 错误码    
  6.      */    
  7.     @ApiModelProperty("错误码")    
  8.     private Integer code;    
  9.     /**    
  10.      * 提示信息    
  11.      */    
  12.     @ApiModelProperty("提示信息")    
  13.     private String message;    
  14.     /**    
  15.      * 具体的内容    
  16.      */    
  17.     @ApiModelProperty("响应数据")   
  18.     private Object data;    
  19. }   

抽象表单 BaseForm 

  1. public abstract class BaseForm<T> {      
  2.     /**    
  3.      * 获取实例    
  4.      * @return 返回实体类    
  5.      */    
  6.     public abstract T buildEntity();    
  7. }   

有小伙伴可能有疑问了,这个类有啥用呢。先看一下,下面的代码。 

  1. /**    
  2.  * 添加用户    
  3.  * @param userForm 表单数据    
  4.  * @return true 或者 false    
  5.  */   
  6.  @Override    
  7. public boolean addUser(AddUserForm userForm) {    
  8.     User user = new User();    
  9.     user.setNickname(userForm.getNickname());    
  10.     user.setBirthday(userForm.getBirthday());    
  11.     user.setUsername(userForm.getUsername());    
  12.     user.setPassword(userForm.getPassword());    
  13.     return save(user);    
  14. }   

重构一下,感觉清爽了一些。 

  1. /**    
  2.  * 添加用户    
  3.  * @param userForm 表单数据    
  4.  * @return true 或者 false    
  5.  */    
  6. @Override    
  7. public boolean addUser(AddUserForm userForm) {    
  8.     User user = new User();    
  9.     BeanUtils.copyProperties(this,user);    
  10.     return save(user);    
  11. }   

使用BaseForm进行重构 AddUserForm 继承 BaseForm并重写buildEntity 

  1. @Data    
  2. @EqualsAndHashCode(callSuper = false)    
  3. public class AddUserForm extends BaseForm<User> {    
  4.     /**    
  5.      * 昵称    
  6.      */    
  7.     private String nickname;    
  8.     /**    
  9.      * 生日    
  10.      */    
  11.     private Date birthday;    
  12.     /**    
  13.      * 用户名    
  14.      */    
  15.     private String username;    
  16.     /**    
  17.      * 密码    
  18.      */    
  19.     private String password;    
  20.     /**    
  21.      * 构造实体    
  22.      * @return 实体对象    
  23.      */    
  24.     @Override    
  25.     public User buildEntity() {   
  26.         User user = new User();    
  27.         BeanUtils.copyProperties(this,user);    
  28.         return user;    
  29.     }    
  30. }    
  1. /**    
  2.  * 添加用户    
  3.  * @param userForm 表单数据    
  4.  * @return true 或者 false    
  5.  */    
  6. @Override    
  7. public boolean addUser(AddUserForm userForm) {  
  8.     return save(userForm.buildEntity());    
  9. }   

上面的代码有没有种似曾相识的感觉,很多情况都是将接受到的参数,转变成对应的实体类然后「保存」或者「更新」。

所以对于这类的form可以继承baseform并实现buildEntity()这样可以更加符合面向对象,service不需要关心form如何转变成entity,只需要在使用的时候调用buildEntity()即可,尤其是在form -> entity相对复杂的时候,这样做可以减少service内的代码。让代码逻辑看起来更加清晰。

通用的分页对象

涉及到查询的时候,绝大多数都需要用到分页,所以说封装分页对象就很有必要。可以注意下 PageForm.calcCurrent()、PageVo.setCurrentAndSize()、PageVo.setTotal()这个几个方法。

PageForm 

  1. @Data    
  2. @ApiModel(value = "分页数据"description = "分页需要的表单数据")    
  3. public class PageForm<T extends PageForm<?>>{    
  4.     /**    
  5.      * 页码    
  6.      */    
  7.     @ApiModelProperty(value = "页码 从第一页开始 1")    
  8.     @Min(value = 1message = "页码输入有误")    
  9.     private Integer current;    
  10.     /**    
  11.      * 每页显示的数量    
  12.      */    
  13.     @ApiModelProperty(value = "每页显示的数量 范围在1~100")    
  14.     @Range(min = 1max = 100message = "每页显示的数量输入有误")    
  15.     private Integer size;    
  16.     /**    
  17.      * 计算当前页 ,方便mysql 进行分页查询    
  18.      * @return 返回 pageForm    
  19.      */    
  20.     @ApiModelProperty(hidden = true)    
  21.     public T calcCurrent(){    
  22.         current = (current - 1 ) * size;    
  23.         return (T) this;    
  24.     }    
  25. }   

PageVo 

  1. @Data    
  2. public class PageVo<T> {   
  3.     /**    
  4.      * 分页数据    
  5.      */    
  6.     @ApiModelProperty(value = "分页数据")    
  7.     private List<T> records;    
  8.     /**    
  9.      * 总条数    
  10.      */    
  11.     @ApiModelProperty(value = "总条数")    
  12.     private Integer total;    
  13.     /**    
  14.      * 总页数    
  15.      */    
  16.     @ApiModelProperty(value = "总页数")    
  17.     private Integer pages;    
  18.     /**    
  19.      * 当前页    
  20.      */    
  21.     @ApiModelProperty(value = "当前页")    
  22.     private Integer current;    
  23.     /**    
  24.      * 查询数量    
  25.      */    
  26.     @ApiModelProperty(value = "查询数量")    
  27.     private Integer size;    
  28.     /**    
  29.      * 设置当前页和每页显示的数量    
  30.      * @param pageForm 分页表单    
  31.      * @return 返回分页信息   
  32.       */   
  33.     @ApiModelProperty(hidden = true)    
  34.     public PageVo<T> setCurrentAndSize(PageForm<?> pageForm){    
  35.         BeanUtils.copyProperties(pageForm,this);    
  36.         return this;    
  37.     }    
  38.     /**    
  39.      * 设置总记录数    
  40.      * @param total 总记录数    
  41.      */    
  42.     @ApiModelProperty(hidden = true)    
  43.     public void setTotal(Integer total) {    
  44.         this.total = total;    
  45.         this.setPages(this.total % this.size > 0 ? this.total / this.size + 1 : this.total / this.size);    
  46.     }    
  47. }   

案例

ListUserForm 

  1. @Data    
  2. @ApiModel("获取用户列表需要的表单数据")   
  3. @EqualsAndHashCode(callSuper = false)    
  4. public class ListUserForm extends PageForm<ListUserForm> {    
  5.     /**    
  6.      * 用户状态    
  7.      */    
  8.     @ApiModelProperty("用户状态")    
  9.     @NotEmpty(message = "用户状态不能为空")    
  10.     @Range(min =  -1 , max = 1 , message = "用户状态有误")    
  11.     private String status;    
  12. }   

UserServiceImpl 

  1. /**    
  2.  * 获取用户列表    
  3.  * @param listUserForm 表单数据    
  4.  * @return 用户列表    
  5.  */    
  6. @Override    
  7. public PageVo<UserVo> listUser(ListUserForm listUserForm) {   
  8.     PageVo<UserVo> pageVo = new PageVo<UserVo>().setCurrentAndSize(listUserForm);   
  9.     pageVo.setTotal(countUser(listUserForm.getStatus()));    
  10.     pageVo.setRecords(userMapper.listUser(listUserForm.calcCurrent()));    
  11.     return pageVo;    
  12. }    
  13. /**    
  14.  * 获取用户数量    
  15.  * @param status 状态    
  16.  * @return 用户数量    
  17.  */    
  18. private Integer countUser(String status){    
  19.     return count(new QueryWrapper<User>().eq("status",status));    
  20. }   

UserController 

  1. /**    
  2.  * 获取用户列表    
  3.  * @param listUserForm 表单数据    
  4.  * @return 用户列表    
  5.  */    
  6. @ApiOperation("获取用户列表")    
  7. @GetMapping("/listUser")    
  8. @ApiResponses(    
  9.         @ApiResponse(code = 200message = "操作成功"response = UserVo.class)    
  10. )    
  11. public ResultVo listUser(@Validated ListUserForm listUserForm){   
  12.     return ResultVoUtil.success(userService.listUser(listUserForm));    
  13. }   

注意的点

  •  PageVo在实例化的时候需要设置「当前页」和「每页显示的数量」 可以调用setCurrentAndSize()完成。
  •  进行分页查询的时候,需要计算偏移量。listUserForm.calcCurrent()

为什么要计算偏移量呢?

  •  假如查询第1页每页显示10条记录,前端传递过来的参数是current=1&amp;&amp;size=10,这个时候limit 1,10没有问题。
  •  假如查询第2页每页显示10条记录,前端传递过来的参数是current=2&amp;&amp;size=10,这个时候limit 2,10就有问题,实际应该是limit 10,10。calcCurrent()的作用就是如此。

为什么不用MybatisPlus自带的分页插件呢?

    ❝    自带的分页查询在大量数据下,会出现性能问题。    ❞

常用工具类

常用工具类可以根据自己的开发习惯引入。

推荐阅读:国人开源了一款小而全的 Java 工具类库

异常处理

异常处理的大致流程主要如下。

  •  异常信息抛出 -> ControllerAdvice 进行捕获格式化输出内容
  •  手动抛出CustomException并传入ReulstEnum ——> 进行捕获错误信息输出错误信息。

自定义异常 

  1. @Data    
  2. @EqualsAndHashCode(callSuper = false 
  3. public class CustomException extends RuntimeException {    
  4.     /**    
  5.      * 状态码    
  6.      */    
  7.     private final Integer code;  
  8.     /**    
  9.      * 方法名称    
  10.      */    
  11.     private final String method;    
  12.     /**    
  13.      * 自定义异常    
  14.      *    
  15.      * @param resultEnum 返回枚举对象    
  16.      * @param method     方法    
  17.      */    
  18.     public CustomException(ResultEnum resultEnum, String method) {    
  19.         super(resultEnum.getMsg());    
  20.         this.code = resultEnum.getCode();   
  21.          this.method = method;    
  22.     }    
  23.     /**    
  24.      * @param code    状态码   
  25.      * @param message 错误信息    
  26.      * @param method  方法    
  27.      */    
  28.     public CustomException(Integer code, String message, String method) {    
  29.         super(message);   
  30.         this.code = code;    
  31.         this.method = method;   
  32.      }    
  33. }   

错误信息枚举

根据业务进行添加。 

  1. @Getter    
  2. public enum ResultEnum {    
  3.     /**    
  4.      * 未知异常  
  5.      */    
  6.     UNKNOWN_EXCEPTION(100, "未知异常"),    
  7.     /**    
  8.      * 添加失败    
  9.      */    
  10.     ADD_ERROR(103, "添加失败"),    
  11.     /**    
  12.      * 更新失败    
  13.      */    
  14.     UPDATE_ERROR(104, "更新失败"),    
  15.     /**    
  16.      * 删除失败    
  17.      */    
  18.     DELETE_ERROR(105, "删除失败"), 
  19.     /**    
  20.      * 查找失败    
  21.      */    
  22.     GET_ERROR(106, "查找失败"),    
  23.     ;    
  24.     private Integer code;    
  25.     private String msg;    
  26.     ResultEnum(Integer code, String msg) {    
  27.         this.code = code;    
  28.         this.msg = msg;    
  29.     }   
  30.     /**    
  31.      * 通过状态码获取枚举对象    
  32.      * @param code 状态码    
  33.      * @return 枚举对象    
  34.      */    
  35.     public static ResultEnum getByCode(int code){    
  36.         for (ResultEnum resultEnum : ResultEnum.values()) {    
  37.             if(code == resultEnum.getCode()){    
  38.                 return resultEnum;    
  39.             }    
  40.         }    
  41.         return null;   
  42.     }    
  43. }   

全局异常拦截

全局异常拦截是使用@ControllerAdvice进行实现,常用的异常拦截配置可以查看 GlobalExceptionHandling。 

  1. @Slf4j    
  2. @RestControllerAdvice   
  3. public class GlobalExceptionHandling {   
  4.     /**    
  5.      * 自定义异常    
  6.      */    
  7.     @ExceptionHandler(value = CustomException.class)    
  8.     public ResultVo processException(CustomException e) { 
  9.         log.error("位置:{} -> 错误信息:{}", e.getMethod() ,e.getLocalizedMessage());   
  10.         return ResultVoUtil.error(Objects.requireNonNull(ResultEnum.getByCode(e.getCode())));    
  11.     }    
  12.     /**    
  13.      * 通用异常    
  14.      */    
  15.     @ResponseStatus(HttpStatus.OK)    
  16.     @ExceptionHandler(Exception.class)   
  17.     public ResultVo exception(Exception e) {    
  18.         e.printStackTrace();    
  19.         return ResultVoUtil.error(ResultEnum.UNKNOWN_EXCEPTION);    
  20.     }    
  21. }   

案例

Controller 

  1. /**    
  2.  * 删除用户    
  3.  * @param id 用户编号    
  4.  * @return 成功或者失败   
  5.  */    
  6. @ApiOperation("删除用户")  
  7. @DeleteMapping("/deleteUser/{id}")    
  8. public ResultVo deleteUser(@PathVariable("id") String id){   
  9.     userService.deleteUser(id);    
  10.     return ResultVoUtil.success();    
  11. }   

Service 

  1. /**    
  2.  * 删除用户    
  3.  * @param id id    
  4.  */    
  5. @Override    
  6. public void deleteUser(String id) {    
  7.     // 如果删除失败抛出异常。 -- 演示而已不推荐这样干    
  8.     if(!removeById(id)){    
  9.         throw new CustomException(ResultEnum.DELETE_ERROR, MethodUtil.getLineInfo());   
  10.     }    
  11. }   

结果

「将报错代码所在的文件第多少行都打印出来。方便排查。」

注意的点

所有手动抛出的错误信息,都应在错误信息枚举ResultEnum进行统一维护。不同的业务使用不同的错误码。方便在报错时进行分辨。快速定位问题。

多环境配置

SpringBoot多环境配置

对于一个项目来讲基本都4有个环境dev,test,pre,prod,对于SpringBoot项目多建立几个配置文件就可以了。

然后启动的时候可以通过配置spring.profiles.active 来选择启动的环境。这个详细教程请关注公众号Java技术栈回复boot获取系列教程。

 

  1. java -jar BasicProject.jar --spring.profiles.active=prod   

Maven多环境配置

假如想在打包的时候动态指定环境,这个时候就需要借助Maven的xml来实现。这个请关注公众号Java技术栈回复mvn获取一份完整详细教程。

配置XML 

  1. <!--  配置环境  -->    
  2. <profiles>    
  3.     <profile>    
  4.         <!-- 开发 -->    
  5.         <id>dev</id>    
  6.         <activation>    
  7.             <activeByDefault>true</activeByDefault>    
  8.         </activation>    
  9.         <properties>    
  10.             <activatedProperties>dev</activatedProperties>  
  11.         </properties>    
  12.     </profile>    
  13.     <profile>    
  14.         <!-- 测试 -->    
  15.         <id>test</id>    
  16.         <properties>    
  17.             <activatedProperties>test</activatedProperties>    
  18.         </properties>    
  19.     </profile>    
  20.     <profile>    
  21.         <!-- 准生产 -->    
  22.         <id>pre</id>    
  23.         <properties>    
  24.             <activatedProperties>pre</activatedProperties>    
  25.         </properties>    
  26.     </profile>    
  27.     <profile>    
  28.         <!-- 生产 -->    
  29.         <id>prod</id>    
  30.         <properties>    
  31.             <activatedProperties>prod</activatedProperties>    
  32.         </properties>    
  33.     </profile>    
  34. </profiles>   

更改application.yml 

  1. spring:    
  2.   profiles:  
  3.      # 选择环境    
  4.     active: @activatedProperties@   

使用案例 

  1. mvn clean package -P prod   
  2. mvn clean package -P pre    
  3. mvn clean package -P test   

打包完可以解压开查看application.yml 会发现spring.profiles.active=@activatedProperties@ 发生了改变。

日志配置

采用logback日志配置,点击这里参考这篇文章。

JenkinsFile

JenkinsFile肯定顾名思义是给jenkins用的。主要是配置项目根据如何进行构建并发布到不同的环境。需要去了解pipeline语法,以及如何配置jenkins。

结尾

如果觉得对你有帮助,可以随手点个在看哦,谢谢。 

 

责任编辑:庞桂玉 来源: Java技术栈
相关推荐

2020-11-13 07:08:51

Spring Boot应用Spring

2022-06-06 08:42:04

spring-boo开发接口防盗刷

2020-09-27 14:13:50

Spring BootJava框架

2022-06-23 08:42:08

配置加密解密

2019-07-15 11:04:37

Spring BootTomcat开发

2021-05-06 10:52:09

Java Spring Bo框架

2023-04-28 12:01:56

Spring项目编译

2023-10-18 15:25:29

数据源数据库

2022-05-09 11:01:18

配置文件数据库

2020-06-22 07:55:28

接口爬虫

2014-07-02 10:03:42

App推广渠道

2022-09-22 13:28:34

Redis分布式锁

2024-02-04 09:19:00

Nacos动态化线程池

2022-09-29 08:28:57

SpringRedis分布式

2020-03-16 17:20:02

异常处理Spring Boot

2011-03-24 09:34:41

SPRING

2021-02-03 09:04:11

解密Spring配置

2022-12-14 09:06:58

接口Spring解密

2020-09-02 08:09:10

攻击防御Shiro

2019-10-15 09:30:15

开源Spring BooJava
点赞
收藏

51CTO技术栈公众号