springboot集成Lombok、MybaitsPlus、SwaggerUI
基础环境:JDK8或者JDK11版本 + Maven3.5(采⽤默认) + IDEA旗舰版 + Mysql5.7以上版本
创建springboot项目
-
在线构建⼯具 https://start.spring.io/
-
修改pom.xml中内容
<!-- 代码库 --> <repositories> <repository> <id>maven-ali</id> <url>http://maven.aliyun.com/nexus/content/grou ps/public//</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> <updatePolicy>always</updatePolicy> <checksumPolicy>fail</checksumPolicy> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>public</id> <name>aliyun nexus</name> <url>http://maven.aliyun.com/nexus/content/grou ps/public/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </pluginRepository> </pluginRepositories>
集成Lombok
-
pom.xml引入对应依赖
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.16</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.projec tlombok/lombok/1.18.16--> <!--scope=provided,说明它只在编译阶段⽣效,不需要 打⼊包中, Lombok在编译期将带Lombok注解的Java⽂件正 确编译为完整的Class⽂件-->
-
添加IDE⼯具对Lombok的⽀持
点击File-- Settings设置界⾯,找到Plugins安装Lombok插件,然后
重启idea
-
IDEA⾥需要在设置中启⽤annotation processors,记得重启IDEA
-
lombok的常⻅注解
@Getter/@Setter 作⽤类上,⽣成所有成员变量的getter/setter⽅法 作⽤于成员变量上,⽣成该成员变量的getter/setter⽅ 法. @NonNull 作⽤于⽅法上或者属性,⽤于⾮空判断,如果为空则抛异常 @NoArgsConstructor ⽣成⽆参构造器 @AllArgsConstructor ⽣成全参构造器 @RequiredArgsConstructor 指定参数的构造函数,有以下的特征的字段(final类型未被初始化的属性, 标记了@NonNull的属 性 注意:@NoArgsConstructor不能加) @ToString 作⽤于类,覆盖默认的toString()⽅法 不包括某个字段(@ToString(exclude = {"age"})) 只输出某个字段(@ToString(of = {"name"})) @EqualsAndHashCode 作⽤于类,覆盖默认的equals和hashCode, 作⽤于全部属 性 不包括某个属性(@EqualsAndHashCode(exclude = {"age"})) 只输出某个属性(@EqualsAndHashCode(of = {"name"})) @Log / @Slf4j 作⽤于类上,⽣成⽇志变量, ⽤于记录⽇志
集成增强版ORM框架-MybatisPlus
官⽹ https://baomidou.com/
-
添加依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector- java</artifactId> </dependency> <!--mybatis plus和springboot整合--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot- starter</artifactId> <version>3.4.1</version> </dependency>
-
增加数据库配置
server.port=8081 ==============================数据库相关配置============================= spring.datasource.driver-class-name =com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1: 3306/test? useUnicode=true&characterEncoding=utf- 8&useSSL=false spring.datasource.username =root spring.datasource.password =root
-
建⽴好包,配置springboot扫描路径
@SpringBootApplication @MapperScan("com.sbootBase.mapper") public class SbootBaseApplication { public static void main(String[] args) { SpringApplication.run(SbootBaseApplication.class, args); } }
-
统⼀接⼝返回协议-JsonData
@Data /** * 会⽣成⼀个包含所有变量 */ @AllArgsConstructor /** * ⽣成⼀个⽆参数的构造⽅法 */ @NoArgsConstructor public class JsonData { /** * 状态码 0 表示成功,1表示处理中,-1表示失败 */ private Integer code; /** * 数据 */ private Object data; /** * 描述 */ private String msg; // 成功,传⼊数据 public static JsonData buildSuccess() { return new JsonData(0, null, null); } // 成功,传⼊数据 public static JsonData buildSuccess(Object data) { return new JsonData(0, data, null); } // 失败,传⼊描述信息 public static JsonData buildError(String msg) { return new JsonData(-1, null, msg); } // 失败,传⼊描述信息,状态码 public static JsonData buildError(String msg, Integer code) { return new JsonData(code, null, msg); } }
-
BannerDO类编写
@Data /** * 表名映射 */ @TableName("banner") public class BannerDO { // @TableId(value = "id",type = IdType.AUTO) private Integer id; @TableField("img") private String img; private String url; private Integer weight; /** * exist 是否为数据库表字段 * 默认 true 存在,false 不存在 */ @TableField(exist = false) private Date createTime; }
-
controller-list接⼝
@RestController @RequestMapping("/api/banner/v1") public class BannerController { @Autowired private BannerService bannerService; @RequestMapping("list") public JsonData list(){ return JsonData.buildSuccess(bannerService.list()); } }
-
service层
@Service public class BannerServiceImpl implements BannerService { @Autowired private BannerMapper bannerMapper; @Override public List<BannerDO> list() { //查询全部 List<BannerDO> list = bannerMapper.selectList(new QueryWrapper<BannerDO>()); return list; } }
-
mapper层
public interface BannerMapper extends BaseMapper<BannerDO> { }
-
集成Spring Boot Test单元测试和控制台sql⽇志打印
添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter- test</artifactId> </dependency>
-
新建测试类
package com.jflu.sbootBase; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.jflu.sbootBase.entity.BannerDO; import com.jflu.sbootBase.mapper.BannerMapper; import com.jflu.sbootBase.service.BannerService; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author jflu6 * @create 2022-12-02 20:41 */ @SpringBootTest(classes = SbootBaseApplication.class) @Slf4j public class BannerTest { @Autowired private BannerService bannerService; @Autowired private BannerMapper bannerMapper; /** * 根据 ID 查询 */ @Test public void testSelectById() { BannerDO bannerDO = bannerMapper.selectById("1"); log.info("bannerDO {}", bannerDO); } /** * 查询(根据ID 批量查询) */ @Test public void testSelectBatchIds() { List<BannerDO> bannerDOS = bannerMapper.selectBatchIds(Arrays.asList("1", "2")); log.info("bannerDO {}", bannerDOS); } /** * 根据 entity 条件,查询一条记录 */ @Test public void testSelectOne() { BannerDO bannerDO = bannerMapper.selectOne(new QueryWrapper<BannerDO>().eq("id", "1")); log.info("bannerDO: {}", bannerDO); } /** * 根据 Wrapper 条件,查询总记录数 * queryWrapper 实体对象封装操作类(可以为 null) */ @Test public void testSelectCount() { Integer integer = bannerMapper.selectCount(null); log.info("bannerDO: {}", integer); } @Test public void testList() { List<BannerDO> list = bannerService.list(); log.info(list.toString()); } /** * 插入一条记录 */ @Test public void testInsert() { BannerDO bannerDO = new BannerDO(); bannerDO.setImg("xxxxxx"); bannerDO.setUrl("xxxxxxx"); bannerDO.setWeight(2); int insert = bannerMapper.insert(bannerDO); log.info("bannerDO:{}", bannerDO); } /** * 根据ID删除数据 */ @Test public void testDeleteById() { int i = bannerMapper.deleteById("4"); log.info("bannerDO:{}", i); } /** * 根据Map条件,删除记录 */ @Test public void testDeleteByMap() { Map map = new HashMap(); map.put("id", "5"); map.put("weight", "2"); int i = bannerMapper.deleteByMap(map); log.info("bannerDO:{}", i); } @Test public void testUpdate() { BannerDO bannerDO = new BannerDO(); bannerDO.setImg("iiiii"); //空字段不会更新 int i = bannerMapper.update(bannerDO, new QueryWrapper<BannerDO>().eq("id", "1")); log.info("bannerDO:{}", i); } @Test public void testUpdateWrapper() { UpdateWrapper updateWrapper = new UpdateWrapper(); //设置要更新的字段和值,key是db的属性名称 updateWrapper.set("img", "uuuu"); //条件 updateWrapper.eq("id", 1); int i = bannerMapper.update(null, updateWrapper); log.info("bannerDO:{}", i); } /** * 核⼼查询条件类QueryWrapper * eq 等于 * ne 不等于 * gt ⼤于 * ge ⼤于等于 * lt ⼩于 * le ⼩于等于 * or 拼接or * between 两个值中间 * notBetween 不在两个值中间 */ @Test public void testQueryWrapper() { QueryWrapper queryWrapper = new QueryWrapper(); queryWrapper.eq("id", "1"); queryWrapper.or(); queryWrapper.eq("img", "uuuu"); List list = bannerMapper.selectList(queryWrapper); log.info("bannerDO:{}", list); } /** * like 模糊匹配 * notLike 不像 * List<BannerDO> list = * bannerMapper.selectList(new * QueryWrapper<BannerDO>()); * likeLeft 左匹配 * likeRight 右边匹配 * isNull 字段为空 * in in查询 * groupBy 分组 * orderByAsc 升序 * orderByDesc 降序 * having having查询 */ @Test public void testQueryWrapper2() { QueryWrapper queryWrapper = new QueryWrapper(); queryWrapper.likeLeft("url", "xxxx"); queryWrapper.like("img", "uuuu"); List list = bannerMapper.selectList(queryWrapper); log.info("bannerDO:{}", list); } /*** * 测试分⻚ */ @Test public void testPage() { QueryWrapper<BannerDO> wrapper = new QueryWrapper<>(); wrapper.eq("weight", 4); //第1⻚,每⻚2条 Page<BannerDO> page = new Page<>(2, 2); IPage<BannerDO> bannerDOIPage = bannerMapper.selectPage(page, null); log.info("总条数:{}",bannerDOIPage.getTotal()); log.info("总⻚数: {}" ,bannerDOIPage.getPages()); //获取当前数据 log.info("数据:{}",bannerDOIPage.getRecords().toString()); } @Test public void testList2(){ List<BannerDO> list = bannerMapper.list(); log.info("数据:{}",list.toString()); } /*** * 测试查询指定字段 */ @Test public void testSelect() { QueryWrapper<BannerDO> wrapper = new QueryWrapper<>(); //第1⻚,每⻚2条 Page<BannerDO> page = new Page<>(2, 2); IPage<BannerDO> bannerDOIPage = bannerMapper.selectPage(page, wrapper.select("id","url")); log.info("总条数:{}",bannerDOIPage.getTotal()); log.info("总⻚数: {}" ,bannerDOIPage.getPages()); //获取当前数据 log.info("数据:{}",bannerDOIPage.getRecords().toString()); } }
-
Mybatis plus配置控制台打印⽇志
#配置mybatis plus打印sql⽇志 mybatis-plus.configuration.log- impl=org.apache.ibatis.logging.stdout.StdOutImpl
-
Mybatis plus常⽤注解
@TableName ⽤于定义表名 @TableId ⽤于定义表的主键 属性 主键策略 @TableField ⽤于定义表的⾮主键字段 value ⽤于定义主键字段名 type ⽤于定义主键类型(主键策略 IdType) IdType.AUTO 主键⾃增,系统分配,不需要⼿ 动输⼊ IdType.NONE 未设置主键 IdType.INPUT 需要⾃⼰输⼊ 主键值 IdType.ASSIGN_ID 系统分配 ID,⽤于数值型数据 (Long,对应 mysql 中 BIGINT 类型) IdType.ASSIGN_UUID 系统分配 UUID,⽤于字符串型 数据(String,对应 mysql 中 varchar(32) 类型) 属性 value ⽤于定义⾮主键字段名,⽤于别名匹配,假如java对 象属性和数据库属性不⼀样 exist ⽤于指明是否为数据表的字段, true 表示是, false 为不是,假如某个java属性在数据库没对应的字段则 要标记为faslse fill ⽤于指定字段填充策略(FieldFill,⽤的不多) 字段填充策略:⼀般⽤于填充 创建时间、修改时间等字段 FieldFill.DEFAULT 默认不填充 FieldFill.INSERT 插⼊时填充 FieldFill.UPDATE 更新时填充 FieldFill.INSERT_UPDATE 插⼊、更新时填充。
-
MybatisPlus查询封装类QueryWrapper⽐较API讲解
QueryWrapper介绍 可以封装sql对象,包括where条件,order by排序, UpdateWrapper updateWrapper = new UpdateWrapper(); //设置要更新的字段和值,key是db的属性名称 updateWrapper.set("img","uuuu"); //条件 updateWrapper.eq("id",1); bannerMapper.update(null,updateWrapper); select哪些字段等等 查询包装类,可以封装多数查询条件,泛型指定返回的 实体类 核⼼API eq 等于 ne 不等于 gt ⼤于 ge ⼤于等于 lt ⼩于 le ⼩于等于 or 拼接or between 两个值中间 notBetween 不在两个值中间
-
QueryWrapper的模糊查询和其他API讲解
可以封装sql对象,包括where条件,order by排序, select哪些字段等等 查询包装类,可以封装多数查询条件,泛型指定返回的 实体类 核⼼API like 模糊匹配 notLike 不像 List<BannerDO> list = bannerMapper.selectList(new QueryWrapper<BannerDO>()); likeLeft 左匹配 likeRight 右边匹配 isNull 字段为空 in in查询 groupBy 分组 orderByAsc 升序 orderByDesc 降序 having having查询
-
案例实战 Mybatis plus 分⻚插件配置
@Configuration public class MybatisPlusPageConfig { /* 旧版本配置 @Bean public PaginationInterceptor paginationInterceptor(){ return new PaginationInterceptor(); }*/ /** * 新的分⻚插件 */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; }
-
MybatisPlus ⾃定义xml的sql脚本
新建xml
```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接⼝的路径,记得修改-->
<mapper namespace="com.jflu.sbootBase.mapper.BannerMapper">
<select id="list" resultType="com.jflu.sbootBase.entity.BannerDO">
select * from banner
</select>
</mapper>
```
配置⽂件告诉mapper.xml路径(如果采⽤默认路径可以不配)在properties中
```properties
#配置plus打印sql⽇志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#默认配置路径
mybatis-plus.mapper-locations=classpath*:/mapper/*Mapper.xml
```
配置Myabits的全局配置⽂件(注意:config-location和configuration不能同时出现,需要注释配置⽂件⾥的相关配置)
```properties
server.port=8081
#==============================数据库相关配置===========
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/jflu_test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username =root
spring.datasource.password =root
#配置mybatis plus打印sql日志
#mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#配置最新全局配置?件打印sql日志!!!!
mybatis-plus.config-location =classpath:mybatis-config.xml
#默认配置路径
mybatis-plus.mapper-locations=classpath:/mapper/**/*.xml
#mybatis plus下划线转驼峰配置,默认就是true,config-location和configuration配置不能共存,如果想放开驼峰注解那就要使用上面
# configuration的配置方案mybatis-plus.configuration.log-impl
#mybatis-plus.configuration.map-underscore-to-camel-case=true
#配置全局默认主键类型,实体类就不?加 @TableId(value ="id", type = IdType.AUTO)
mybatis-plus.global-config.db-config.id-type=auto
#swagger配置
spring.application.name=springbootBase
# ===== ?定义swagger配置 ===== #
#enable是否开始api false 否
swagger.enable=true
swagger.application-name=${spring.application.name}
swagger.application-version=1.0
swagger.application-description=api info
```
创建mybatis-config.xml
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-
//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!--控制台输出⽇志-->
<setting name="logImpl"value="STDOUT_LOGGING"/>
</settings>
</configuration>
```
-
Mybatis-plus-generator代码⾃动化⽣成⼯具
添加依赖
<!-- 代码⾃动⽣成依赖 begin --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus- generator</artifactId> <version>3.4.1</version> </dependency> <!-- velocity --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine- core</artifactId> <version>2.0</version> </dependency> <!-- 代码⾃动⽣成依赖 end-->
MyBatisPlusGenerator类
package com.jflu.sbootBase.config; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.DataSourceConfig; import com.baomidou.mybatisplus.generator.config.GlobalConfig; import com.baomidou.mybatisplus.generator.config.PackageConfig; import com.baomidou.mybatisplus.generator.config.StrategyConfig; import com.baomidou.mybatisplus.generator.config.rules.DateType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import java.util.Scanner; /** * @author jflu6 * @create 2022-12-04 19:55 */ public class MyBatisPlusGenerator { public static void main(String[] args) { //1. 全局配置 GlobalConfig config = new GlobalConfig(); // 是否⽀持AR模式 config.setActiveRecord(true) // 作者 .setAuthor("jflu6") // ⽣成路径,最好使⽤绝对路径,window路径是不⼀样的 //TODO TODO TODO TODO .setOutputDir("D:\\data\\file\\demo\\src\\main\\java") // ⽂件覆盖 .setFileOverride(true) // 主键策略 .setIdType(IdType.AUTO) .setDateType(DateType.ONLY_DATE) // 设置⽣成的service接⼝的名字的⾸字⺟是否为I,默认Service是以I开头的 .setServiceName("%sService") //实体类结尾名称 .setEntityName("%sDO") //⽣成基本的resultMap .setBaseResultMap(true) //不使⽤AR模式 .setActiveRecord(false) //⽣成基本的SQL⽚段 .setBaseColumnList(true); //2. 数据源配置 DataSourceConfig dsConfig = new DataSourceConfig(); // 设置数据库类型 dsConfig.setDbType(DbType.MYSQL) .setDriverName("com.mysql.cj.jdbc.Driver") //TODO TODO TODO TODO .setUrl("jdbc:mysql://127.0.0.1:3306/jflu_test?useSSL = false") .setUsername("root") .setPassword("root"); //3. 策略配置globalConfiguration中 StrategyConfig stConfig = new StrategyConfig(); //全局⼤写命名 stConfig.setCapitalMode(true) // 数据库表映射到实体的命名策略 .setNaming(NamingStrategy.underline_to_camel) //使⽤lombok .setEntityLombokModel(true) //使⽤restcontroller注解 .setRestControllerStyle(true) // ⽣成的表, ⽀持多表⼀起⽣成,以数组形式填写 //TODO TODO TODO TODO 两个⽅式,直接写,或者使⽤命令⾏输⼊ .setInclude("product", "product_task", "banner"); //.setInclude(scanner("表名,多个英⽂逗号分割").split(", ")); //4. 包名策略配置 PackageConfig pkConfig = new PackageConfig(); pkConfig.setParent("com.jflu") .setMapper("mapper") .setService("service") .setController("controller") .setEntity("model") .setXml("mapper"); //5. 整合配置 AutoGenerator ag = new AutoGenerator(); ag.setGlobalConfig(config) .setDataSource(dsConfig) .setStrategy(stConfig) .setPackageInfo(pkConfig); //6. 执⾏操作 ag.execute(); System.out.println("=======相关代码⽣成完毕 ========"); } /** * <p> * 读取控制台内容 * </p> */ public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append("请输⼊" + tip + ":"); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (StringUtils.isNotBlank(ipt)) { return ipt; } } throw new MybatisPlusException("请输⼊正确的" + tip + "!"); } }
集成Swagger3接口文档规范
-
地址
https://swagger.io/tools/swagger-ui/
-
SpringBoot添加pom⽂件依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
- 配置⽂件增加配置(在properties中)
#swagger配置
spring.application.name=springbootBase
# ===== ?定义swagger配置 ===== #
#enable是否开始api false 否
swagger.enable=true
swagger.application-name=${spring.application.name}
swagger.application-version=1.0
swagger.application-description=api info
- 创建配置类
package com.jflu.sbootBase.config;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* @author jflu6
* @create 2022-12-05 21:21
*/
@Component
@EnableOpenApi
@ConfigurationProperties("swagger")
@Data
public class SwaggerConfiguration {
/**
* 是否开启swagger,⽣产环境⼀般关闭,所以这⾥定义
* ⼀个变量
*/
private Boolean enable;
/**
* 项⽬应⽤名
*/
private String applicationName;
/**
* 项⽬版本信息
*/
private String applicationVersion;
/**
* 项⽬描述信息
*/
private String applicationDescription;
@Bean
public Docket docket() {
return new
Docket(DocumentationType.OAS_30)
.pathMapping("/")
.enable(enable) // 定义是否开启swagger,false为关 闭,可以通过变量控制,线上关闭
.apiInfo(apiInfo()) //配置api⽂档元信息
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(applicationName)
.description(applicationDescription)
.contact(new Contact("jflu6","127.0.0.1","jflu6@163.com"))
.version(applicationVersion)
.build();
}
}
-
访问路径
http://localhost:8081/swagger-ui/index.html
-
功能模块相关接⼝⽂档配置(例如用户)
package com.jflu.sbootBase.controller; import com.jflu.sbootBase.request.SaveUserRequest; import com.jflu.sbootBase.util.JsonData; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.web.bind.annotation.*; /** * @author jflu6 * @create 2022-12-06 8:38 */ @RestController //@Api 模块配置,⽤在controller类,描述API接⼝ @Api(tags = "⽤户模块", value = "⽤户UserController") public class UserController { // @ApiOperation 接⼝配置,⽤在⽅法上,描述接⼝⽅法上 @ApiOperation("分⻚⽤户列表") @GetMapping("list") public JsonData list() { return JsonData.buildSuccess(); } @ApiOperation("⽤户登录") @PostMapping("login") public JsonData login( //@ApiParam ⽅法参数配置,⽤在⼊参上⾯,描述参数 @ApiParam(name = "phone", value = "⼿机号", example = "13888888888") @RequestParam("phone") String phone, @ApiParam(name = "pwd", value = "密码", example = "123456") @RequestParam("pwd") String pwd) { return JsonData.buildSuccess(); } @ApiOperation("删除⽤户") @DeleteMapping("/delete/{id}") public JsonData deleteById(@PathVariable int id) { return JsonData.buildSuccess(); } @ApiOperation("增加⽤户") @PostMapping("/save") public JsonData save(@RequestBody SaveUserRequest userRequest) { return JsonData.buildSuccess(); } }
-
APiModel和ApiModelProperty对象注解介绍
@ApiModel()
⽤于类 表示对类进⾏说明,⽤于参数⽤实体类接
收,value–表示对象名,description–描述
这种⼀般⽤在post创建的时候,使⽤对象提交这样
的场景
@ApiModelProperty()
⽤于⽅法,字段; 表示对model属性的说明或者数
据操作更改
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏
package com.jflu.sbootBase.request;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* @author jflu6
* @create 2022-12-06 9:12
*/
@Data
@ApiModel("⽤户基本信息")
public class SaveUserRequest {
private int age;
private String pwd;
@ApiModelProperty(value = "【必填】邮箱", required = true)
private String email;
@ApiModelProperty("⼿机号")
private String phone;
@ApiModelProperty(value = "创建时间")
private Date createTime;
}