赞
踩
1.Swagger简介
Swagger是一个自动生成Restful接口的文档功能测试框架。
2.引入依赖
新建一个SpringBoot工程,并在pom.xml文件中添加集成Swagger所需要的dependency。
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.6.1</version> </dependency>
3.添加配置
在application.properties文件中添加如下配置信息。
############################################################ # # MySQL配置 # ############################################################ ### 连接信息 spring.datasource.url = jdbc:mysql://localhost:3306/mydb ### 用户名 spring.datasource.username = root ### 密码 spring.datasource.password = admin123 ### 驱动 spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver ############################################################ # # MyBatis配置 # ############################################################ ### po类存放目录 mybatis.type-aliases-package = com.leichuangkj.swagger.dao.po ### mapper(.xml)资源文件存放路径 mybatis.mapper-locations = classpath:mybatis/mapper/*.xml
4.开发服务端通用返回对象
在项目目录“/src/main/java/com/leichuangkj/swagger”下新建common目录,并在common目录下新建ResponseCode枚举类和ServerResponse类,具体代码如下。
public enum ResponseCode { //1.定义枚举值 ERROR(0,"ERROR"), SUCCESS(1,"SUCCESS"); //2.定义枚举属性 private final int code; private final String desc; //3.定义构造函数 ResponseCode(int code, String desc){ this.code = code; this.desc = desc; } //4.定义get方法 public int getCode(){ return code; } public String getDesc(){ return desc; } }
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) //保证序列化json的时候,如果是null的对象,key也会消失 public class ServerResponse<T> implements Serializable { //1.定义属性 private int status; private String message; private T data; //2.定义构造函数 private ServerResponse(int status) { this.status = status; } private ServerResponse(int status, T data) { this.status = status; this.data = data; } private ServerResponse(int status, String message, T data) { this.status = status; this.message = message; this.data = data; } private ServerResponse(int status, String message) { this.status = status; this.message = message; } //3.getter方法 public int getStatus() { return status; } public T getData() { return data; } public String getMessage() { return message; } @JsonIgnore //使之不在json序列化结果当中 //4.判断这个响应是不是一个正确的响应 public boolean isSuccess() { return this.status == ResponseCode.SUCCESS.getCode(); } //5.定义返回对象的方法 public static <T> ServerResponse<T> createBySuccess() { return new ServerResponse<T>(ResponseCode.SUCCESS.getCode()); } public static <T> ServerResponse<T> createBySuccessMessage(String message) { return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), message); } public static <T> ServerResponse<T> createBySuccess(T data) { return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), data); } public static <T> ServerResponse<T> createBySuccess(String message, T data) { return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), message, data); } public static <T> ServerResponse<T> createByError() { return new ServerResponse<T>(ResponseCode.ERROR.getCode(), ResponseCode.ERROR.getDesc()); } public static <T> ServerResponse<T> createByErrorMessage(String errorMessage) { return new ServerResponse<T>(ResponseCode.ERROR.getCode(), errorMessage); } public static <T> ServerResponse<T> createByErrorCodeMessage(int errorCode, String errorMessage) { return new ServerResponse<T>(errorCode, errorMessage); } public static <T> ServerResponse<T> createByErrorCodeMessageData(int errorCode, String errorMessage,T data) { return new ServerResponse<T>(errorCode, errorMessage,data); } }
5.dao层开发
首先在项目目录“/src/main/java/com/leichuangkj/swagger”下新建“/dao/po”目录,并在po目录下新建User实体类,具体代码如下。
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class User {
private Integer id;
private String name;
private String email;
}
然后在dao目录下新建mapper目录,并在mapper目录下新建UserMapper接口,具体代码如下。
@Repository
public interface UserMapper {
User findByName(String id);
}
最后在resource目录下新建“mybatis/mapper”目录,并在mapper目录下新建UserMapper.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="com.leichuangkj.swagger.dao.mapper.UserMapper" > <resultMap id="BaseResultMap" type="com.leichuangkj.swagger.dao.po.User"> <constructor> <idArg column="id" javaType="java.lang.Integer" jdbcType="INTEGER" /> <arg column="name" javaType="java.lang.String" jdbcType="VARCHAR" /> <arg column="email" javaType="java.lang.String" jdbcType="VARCHAR" /> </constructor> </resultMap> <select id="findByName" parameterType="java.lang.String" resultMap="BaseResultMap"> select id, name, email from user where name = #{name,jdbcType=VARCHAR} </select> </mapper>
6.service层开发
在项目目录“/src/main/java/com/leichuangkj/swagger”下新建service目录,并在service目录下新建IUser接口,具体代码如下。
public interface IUser {
ServerResponse findByName(String name);
}
然后在service目录下新建impl目录,并在impl目录下新建UserImpl实现类,具体代码如下。
@Service
public class UserImpl implements IUser {
@Autowired
UserMapper userMapper;
@Override
public ServerResponse findByName(String name) {
User user = userMapper.findByName(name);
if(user == null){
return ServerResponse.createByErrorMessage("没有查询到用户");
}
return ServerResponse.createBySuccess(user);
}
}
7.controller层开发
在项目目录“/src/main/java/com/leichuangkj/swagger”下新建controller目录,并在controller目录下新建UserController类,具体代码如下。
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
UserImpl userImpl;
@ApiOperation(value="findByName", notes="根据用户姓名获取用户详情")
@ApiImplicitParam(name = "name", value = "用户姓名", required = true, dataType = "String")
@RequestMapping(value = "/findByName",method = RequestMethod.POST)
@ResponseBody
public ServerResponse findByName(@RequestBody User user){
return userImpl.findByName(user.getName());
}
}
8.配置类开发
在项目目录“/src/main/java/com/leichuangkj/swagger”下新建Swagger配置类,具体代码如下。
@Configuration @EnableSwagger2 public class Swagger { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.leichuangkj.swagger")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("SpringBoot中使用Swagger构建Restful APIs") .description("更多SpringBoot相关文章请关注:https://blog.csdn.net/Jgx1214/article/details/107122927") .termsOfServiceUrl("https://blog.csdn.net/Jgx1214/article/details/107122927") .version("1.0") .build(); } }
9.启动项目
在启动类SwaggerApplication上添加注解“@MapperScan(basePackages = “com.leichuangkj.swagger.dao.mapper”)”,然后启动项目。
@MapperScan(basePackages = "com.leichuangkj.swagger.dao.mapper")
@SpringBootApplication
public class SwaggerApplication {
public static void main(String[] args) {
SpringApplication.run(SwaggerApplication.class, args);
}
}
10.测试
启动SpringBoot程序,访问“http://localhost:8080/swagger-ui.html”,可以看到如下图所示的可视化管理界面。
11.工程目录结构
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。