SpringBoot开发规范部分通用模板+idea配置【项目通用-1】

news2024/9/29 13:31:49

SpringBoot开发规范通用模板

1 分页插件使用

通过MybatisPlus配置分页插件拦截器

@Configuration
@MapperScan("com.xuecheng.content.mapper")
public class MybatisPlusConfig {


    //定义分页的拦截器
    @Bean
    public MybatisPlusInterceptor getMybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }

}

2 通用返回结果

2.1 带分页通用返回结果

  • PageResult:
@Data
@ToString
public class PageResult<T> {
    // 数据列表
    private List<T> items;

    //总记录数
    private long counts;

    //当前页码
    private long page;

    //每页记录数
    private long pageSize;

    public PageResult(List<T> items, long counts, long page, long pageSize) {
        this.items = items;
        this.counts = counts;
        this.page = page;
        this.pageSize = pageSize;
    }

}

2.2 分页请求参数

PageParams(分页请求参数):

@Data
@ToString
public class PageParams {

    //当前页码默认值
    public static final long DEFAULT_PAGE_CURRENT = 1L;
    //每页记录数默认值
    public static final long DEFAULT_PAGE_SIZE = 10L;

    @ApiModelProperty("当前页码")
    //当前页码
    private Long pageNo = DEFAULT_PAGE_CURRENT;

    @ApiModelProperty("每页记录数")
    //每页记录数默认值
    private Long pageSize = DEFAULT_PAGE_SIZE;

    public PageParams() {

    }

    public PageParams(long pageNo, long pageSize) {
        this.pageNo = pageNo;
        this.pageSize = pageSize;
    }
}

3 全局异常处理

在多模块(微服务项目中一般放在base项目中)
微服务项目搭建解析

3.1 通用异常

public enum CommonError {

	UNKOWN_ERROR("执行过程异常,请重试。"),
	PARAMS_ERROR("非法参数"),
	OBJECT_NULL("对象为空"),
	QUERY_NULL("查询结果为空"),
	REQUEST_NULL("请求参数为空");

	private String errMessage;

	public String getErrMessage() {
		return errMessage;
	}

	private CommonError( String errMessage) {
		this.errMessage = errMessage;
	}

}

3.2 错误响应参数包装

/**
 * 错误响应参数包装
 */
public class RestErrorResponse implements Serializable {

    private String errMessage;

    public RestErrorResponse(String errMessage){
        this.errMessage= errMessage;
    }

    public String getErrMessage() {
        return errMessage;
    }

    public void setErrMessage(String errMessage) {
        this.errMessage = errMessage;
    }
}

3.3 自定义异常

public class XueChengPlusException extends RuntimeException {

    private String errMessage;

    public XueChengPlusException() {
        super();
    }

    public XueChengPlusException(String message) {
        super(message);
        this.errMessage = message;
    }

    public String getErrMessage(){
        return errMessage;
    }

    public static void cast(String errMessage){
        throw new XueChengPlusException(errMessage);
    }
    public static void cast(CommonError commonError){
        throw new XueChengPlusException(commonError.getErrMessage());
    }
}

3.4 全局异常处理器

@Slf4j
 @ControllerAdvice//控制器增强
public class GlobalExceptionHandler {

  //处理XueChengPlusException异常  此类异常是程序员主动抛出的,可预知异常
  @ResponseBody//将信息返回为 json格式
  @ExceptionHandler(XueChengPlusException.class)//此方法捕获XueChengPlusException异常
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//状态码返回500
  public RestErrorResponse doXueChengPlusException(XueChengPlusException e){

   log.error("捕获异常:{}",e.getErrMessage());
   e.printStackTrace();

   String errMessage = e.getErrMessage();

   return new RestErrorResponse(errMessage);
  }


  //捕获不可预知异常 Exception
  @ResponseBody//将信息返回为 json格式
  @ExceptionHandler(Exception.class)//此方法捕获Exception异常
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//状态码返回500
  public RestErrorResponse doException(Exception e){

   log.error("捕获异常:{}",e.getMessage());
   e.printStackTrace();

   return new RestErrorResponse(CommonError.UNKOWN_ERROR.getErrMessage());
  }

    @ResponseBody//将信息返回为 json格式
    @ExceptionHandler(MethodArgumentNotValidException.class)//此方法捕获MethodArgumentNotValidException异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//状态码返回500
    public RestErrorResponse doMethodArgumentNotValidException(MethodArgumentNotValidException e){

        BindingResult bindingResult = e.getBindingResult();
        //校验的错误信息
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        //收集错误
        StringBuffer errors = new StringBuffer();
        fieldErrors.forEach(error->{
            errors.append(error.getDefaultMessage()).append(",");
        });

        return new RestErrorResponse(errors.toString());
    }

}

4 HttpClient插件使用

  • 在idea插件中下载httpclient
  • 编写对应环境配置文件xxxx.json,例如:
{
  "dev": {
    "access_token": "",
    "gateway_host": "localhost:63010",
    "content_host": "localhost:63040",
    "system_host": "localhost:63110",
    "media_host": "localhost:63050",
    "search_host": "localhost:63080",
    "auth_host": "localhost:63070",
    "checkcode_host": "localhost:63075",
    "learning_host": "localhost:63020"
  }
}
  • 点击controller中的图标,自动生成文件或自己创建xxx.http
    在这里插入图片描述
### 课程查询接口
POST {{content_host}}/content/course/list?pageNo=1&pageSize=2
Content-Type: application/json

{
  "auditStatus": "202004",
  "courseName": "",
  "publishStatus": ""
}


### 课程分类 查询
GET {{content_host}}/content/course-category/tree-nodes

5 JSR校验

5.1 概念

JSR (Java Specification Requests) 是一套 JavaBean 参数校验的标准
通过Java提供的注解,来达到参数校验效果

  • @NotEmpty(message = “修改课程名称不能为空”,groups={ValidationGroups.Update.class})
  • @NotEmpty(message = “适用人群不能为空”)
  • @Size(message = “适用人群内容过少”,min = 10)

5.2 校验分组

  • 定义分组:
public class ValidationGroups {

 //用于添加校验
 public interface Inster{};
 //用于修改校验
 public interface Update{};
 public interface Delete{};

}
  • controller中使用

insert分组为例

@PostMapping("/course")
    public CourseBaseInfoDto createCourseBase(@RequestBody @Validated(ValidationGroups.Inster.class) AddCourseDto addCourseDto){

        Long companyId = 22L;
        return courseBaseInfoService.createCourseBase(companyId,addCourseDto);
    }

5.3 实体类校验

@Data
@ToString
@ApiModel(value="AddCourseDto", description="新增课程基本信息")
public class AddCourseDto {


 @NotEmpty(message = "添加课程名称不能为空",groups={ValidationGroups.Inster.class})
 @NotEmpty(message = "修改课程名称不能为空",groups={ValidationGroups.Update.class})
 @ApiModelProperty(value = "课程名称", required = true)
 private String name;

 @NotEmpty(message = "适用人群不能为空")
 @Size(message = "适用人群内容过少",min = 10)
 @ApiModelProperty(value = "适用人群", required = true)
 private String users;

6 Idea通用配置

6.1 常用插件

  • lombok
  • HTTPClient
  • Git、GitHub
  • Lombok
  • SpringBoot Initializr and Assistant
  • Translation
  • MybatisX
  • GeneraterAllSetter
  • JPA Buddy

6.2 文件模板

①mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="">
    
    
</mapper>

②spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

6.3 tips

  • 鼠标控制代码大小
settins - editor - general - MouseControl(change font size...)
  • file tepmlate

settings - file and code templates - Files(添加class模板)

在这里插入图片描述
class:

#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
#parse("File Header.java")
/**
 * @description TODO
 * @author zhouYi
 * @date ${DATE} ${TIME}
 * @version 
 */
public class ${NAME} {
}

interface:

#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
#parse("File Header.java")

/**
 * @description TODO
 * @author ${USER}
 * @date ${DATE} ${TIME}
 * @version 
 */
public interface ${NAME} {
}

7 时间转换配置LocalDateTimeConfig

@Configuration
public class LocalDateTimeConfig {

    /*
     * 序列化内容
     *   LocalDateTime -> String
     * 服务端返回给客户端内容
     * */
    @Bean
    public LocalDateTimeSerializer localDateTimeSerializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    /*
     * 反序列化内容
     *   String -> LocalDateTime
     * 客户端传入服务端数据
     * */
    @Bean
    public LocalDateTimeDeserializer localDateTimeDeserializer() {
        return new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }


    // 配置
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            builder.serializerByType(LocalDateTime.class, localDateTimeSerializer());
            builder.deserializerByType(LocalDateTime.class, localDateTimeDeserializer());
        };
    }

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/339109.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Pascal版本的 - freopen

参数 filename -- 这是包含要打开的文件的名称的字符串。 mode -- 这是包含文件访问模式的字符串。它包括 - 高级编号模式&说明1个 “r” 打开文件进行读取。该文件必须存在。 2个 “w” 创建一个用于写入的空文件。如果已存在同名文件&#xff0c;则删除其内容并将该文件…

【Java容器(jdk17)】ArrayList深入源码,就是这么简单

ArrayList深入源码一、ArrayList源码解析1. MIXIN 的混入2. 属性说明3. 构造方法4. 其他方法&#xff08;核心&#xff09;iterator 和 listIterator 方法add方法remove 方法sort方法其他二、ArrayList 为什么是线程不安全的&#xff1f;体现哪些方面呢&#xff1f;三、ArrayLi…

(day12) 自学Java——集合进阶(双列集合)

目录 1.双列集合特点 Map遍历三种方式 2.HashMap 3.LinkedHashMap 4.TreeMap 5.源码解析 6.可变参数(形参个数可变) 7.Collections 8.综合练习 1.双列集合特点 ①双列集合一次需要存一对数据&#xff0c;分别为键和值 ②键不能重复&#xff0c;值可以重复 ③键和值是一…

全志H616——用C语言的形式操作数据库

sqlite3_open(const char *filename, sqlite3 **ppDb)该例程打开一个指向 SQLite 数据库文件的连接&#xff0c;返回一个用于其他 SQLite 程序的数据库连接对象。sqlite3_close(sqlite3*)该例程关闭之前调用 sqlite3_open() 打开的数据库连接。所有与连接相关的语句都应在连接关…

【Linux】环境变量本地变量

文章目录环境变量基本概念常见环境变量和环境变量相关的命令为什么带./运行我们的可执行程序本地变量环境变量的组织方式环境变量具有全局属性环境变量 基本概念 环境变量(environment variables)一般是指在操作系统中用来指定操作系统运行环境的一些参数 如&#xff1a;我们…

gRPC的简单应用

gRPC的简单应用 gRPC是由开发的一个高性能、通用的开源RPC框架&#xff0c;主要面向移动应用开发且基于HTTP/2协议标准而设计&#xff0c;同时支持大多数流行的编程语言。 官网&#xff1a;https://grpc.io/ 安装protoc 工具 https://protobuf.dev/ 安装Go插件 旧版本直接…

学习HandlerThread

HandlerThread是一个扩展了Thread的类。也就意味着它和普通的Thread类的调用没有什么区别&#xff0c;仍然要调用start()。 如上图所示&#xff0c;扩展后的HandlerThread类有一个Looper和Handler。 关于这一块的知识可以参考一下《关于Handler我们应该知道的知识》 HandlerTh…

普冉PY32系列(五) 使用JLink RTT代替串口输出日志

目录 普冉PY32系列(一) PY32F0系列32位Cortex M0 MCU简介普冉PY32系列(二) Ubuntu GCC Toolchain和VSCode开发环境普冉PY32系列(三) PY32F002A资源实测 - 这个型号不简单普冉PY32系列(四) PY32F002A/003/030的时钟设置普冉PY32系列(五) 使用JLink RTT代替串口输出日志 JLink …

Python-第五天 Python函数

Python-第五天 Python函数一、函数介绍1. 什么事函数二、函数的定义1.函数的定义&#xff1a;2.案例三、函数的参数1.函数的传入参数2.案例升级四、函数的返回值1.什么是返回值2.返回值的语法3.None类型4.None类型的应用场景五、函数说明文档1.函数的说明文档2.在PyCharm中查看…

脑机接口协议V1.0

脑机接口&#xff0c;有时也称作“大脑端口”direct neural interface或者“脑机融合感知”brain-machine interface&#xff0c;它是在人或动物脑&#xff08;或者脑细胞的培养物&#xff09;与外部设备间建立的直接连接通路。在单向脑机接口的情况下&#xff0c;计算机或者接…

leaflet显示高程

很多地图软件都能随鼠标移动动态显示高程。这里介绍一种方法&#xff0c;我所得出的。1 下载高程数据一般有12.5m数据下载&#xff0c;可惜精度根本不够&#xff0c;比如mapbox的免费在线的&#xff0c;或者91卫图提供百度网盘打包下载的&#xff0c;没法用&#xff0c;差距太大…

记录robosense RS-LIDAR-16使用过程3

一、wireshark抓包保存pcap文件并解析ubuntu18安装wireshark&#xff0c;参考下面csdn教程&#xff0c;官网教程我看的一脸蒙&#xff08;可能英语太差&#xff09;https://blog.csdn.net/weixin_46048542/article/details/121730448?spm1001.2101.3001.6650.2&utm_medium…

秒杀项目之服务调用分布式session

目录 nginx动静分离 服务调用 创建配置zmall-cart购物车模块 创建配置zmall-order订单模块 服务调用 spring session实战 什么是Spring Session 为什么要使用Spring Session 错误案例展示 配置spring-session 二级域名问题 用户登录 nginx动静分离 第1步&#xff…

如何用演示程序检测K100|K720|K750电动发卡读写一体机性能

K100|K720|K750电动发卡读写一体机采用工业级设 计&#xff0c;表面烤漆处理&#xff0c;具有良好的耐磨耐腐蚀性。适应各种高、低温&#xff0c; 多灰尘等 恶劣环境。其发卡原理为拟人型摩擦式发卡&#xff0c;对各类变形卡有非常好的适应性。 CNC的精度保证卡距的绝对一致性、…

Filter过滤器完成验证代码的封装

Filter过滤器完成验证代码的封装filter是什么1 使用filter2 filter配置到项目中验证用户权限是需要反复使用的代码块&#xff0c;把他封装到filter中&#xff0c;减少代码冗余filter是什么 init()方法&#xff1a;初始化方法&#xff0c;在创建Filter后立即调用。可用于完成初始…

刚刚,体验了一把Bing chat很爽

文章目录刚刚&#xff0c;体验了一把Bing chat很爽你能做啥&#xff1f;与chatgpt有什么不同&#xff1f;以下是Bingchat的 10个新功能1⃣️在网上搜索结果2⃣️摘要链接3⃣️对话助手4⃣️向您发送实际信息&#xff0c;正确的链接5⃣️在单个查询中执行多个搜索6⃣️玩冒险游戏…

内网渗透(十八)之Windows协议认证和密码抓取-本地认证(NTML哈希和LM哈希)

系列文章第一章节之基础知识篇 内网渗透(一)之基础知识-内网渗透介绍和概述 内网渗透(二)之基础知识-工作组介绍 内网渗透(三)之基础知识-域环境的介绍和优点 内网渗透(四)之基础知识-搭建域环境 内网渗透(五)之基础知识-Active Directory活动目录介绍和使用 内网渗透(六)之基…

【Web测试】各类web控件测试点汇总,软测人必备

一 、界面检查 进入一个页面测试&#xff0c;首先是检查title&#xff0c;页面排版&#xff0c;字段等&#xff0c;而不是马上进入文本框校验 1、页面名称title是否正确 2、当前位置是否可见 您的位置&#xff1a;xxx>xxxx 3、文字格式统一性 4、排版是否整齐 5、列表项显示…

leetcode: 3Sum

leetcode: 3Sum1. 题目描述2. 思考3. 解题3. 总结1. 题目描述 Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i ! j, i ! k, and j ! k, and nums[i] nums[j] nums[k] 0. Notice that the solution set must not contain …

爬虫Python入门好学吗?学什么?

爬虫Python入门好学吗&#xff1f;学爬虫需要具备一定的基础&#xff0c;有编程基础学Python爬虫更容易学。但要多看多练&#xff0c;有自己的逻辑想法。用Python达到自己的学习目的才算有价值。如果是入门学习了解&#xff0c;开始学习不难&#xff0c;但深入学习有难度&#…