一份 Spring Boot 项目搭建模板
点击上方蓝色字体,选择“设置星标”
优质文章,第一时间送达

前言
建立一个全新的项目,或者把旧的庞大的项目,进行拆分成多个项目。在建立新的项目中,经常需要做一些重复的工作,比如说拷贝一下常用的工具类,通用代码等等。所以就可以做一个基础的项目方便使用,在经历新项目的时候,直接在基础项目上进行简单配置就可以开发业务代码了。
基础项目该包含哪些东西。
Swagger在线接口文档。 CodeGenerator 代码生成器。 统一返回。 通用的分页对象。 常用工具类。 全局异常拦截。 错误枚举。 自定义异常。 多环境配置文件。 Maven多环境配置。 日志配置。 JenkinsFile。 
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 {
    
    @ApiModelProperty("用户状态")
    @NotEmpty(message = "用户状态不能为空")
    @Range(min = -1 , max = 1 , message = "用户状态有误")
    private String status;
} SwaggerConfiguration.java.CodeGenerator代码生成器。
entity,service,serviceImpl,mapper,mapper.xml。省去了建立一大堆实体类的麻烦。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);
}@Data
@EqualsAndHashCode(callSuper = false)
public class AddUserForm extends BaseForm{ 
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 Listrecords; 
@ApiModelProperty(value = "总条数")
private Integer total;
@ApiModelProperty(value = "总页数")
private Integer pages;
@ApiModelProperty(value = "当前页")
private Integer current;
@ApiModelProperty(value = "查询数量")
private Integer size;
@ApiModelProperty(hidden = true)
public PageVosetCurrentAndSize(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 {
    
    @ApiModelProperty("用户状态")
    @NotEmpty(message = "用户状态不能为空")
    @Range(min = -1 , max = 1 , message = "用户状态有误")
    private String status;
} UserServiceImpl
@Override
public PageVo listUser(ListUserForm listUserForm)  {
    PageVo pageVo = new PageVo().setCurrentAndSize(listUserForm);
    pageVo.setTotal(countUser(listUserForm.getStatus()));
    pageVo.setRecords(userMapper.listUser(listUserForm.calcCurrent()));
    return pageVo;
}
private Integer countUser(String status){
    return count(new QueryWrapper().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()的作用就是如此。
常用工具类
异常处理
异常信息抛出 -> 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 多环境配置
dev,test,pre,prod,对于SpringBoot项目多建立几个配置文件就可以了。然后启动的时候可以通过配置 spring.profiles.active  来选择启动的环境。
java -jar BasicProject.jar --spring.profiles.active=prod
Maven多环境配置
配置XML
<profiles>
    <profile>
        
        <id>devid>
        <activation>
            <activeByDefault>trueactiveByDefault>
        activation>
        <properties>
            <activatedProperties>devactivatedProperties>
        properties>
    profile>
    <profile>
        
        <id>testid>
        <properties>
            <activatedProperties>testactivatedProperties>
        properties>
    profile>
    <profile>
        
        <id>preid>
        <properties>
            <activatedProperties>preactivatedProperties>
        properties>
    profile>
    <profile>
        
        <id>prodid>
        <properties>
            <activatedProperties>prodactivatedProperties>
        properties>
    profile>
profiles>
更改application.yml
spring:
  profiles:
    # 选择环境
    active: @activatedProperties@使用案例
mvn clean package -P prod
mvn clean package -P pre
mvn clean package -P testapplication.yml 会发现spring.profiles.active=@activatedProperties@ 发生了改变。日志配置
JenkinsFile
代码地址
作者: 不一样的科技宅 
链接:juejin.im/post/6844904083942277127
-END-
springboot开发基础脚手架零基础到项目实战
加我微信回复“springboot脚手架”即可获取
点个在看!?
谢谢支持哟 (*^__^*)
