1、导入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--swagger-ui.html模式 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!--doc.html模式 -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.2</version>
</dependency>
</dependencies>
2、启动类添加@EnableSwagger2注解
package com.swagger.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
3、统一响应
package com.swagger.demo.response;
import lombok.Data;
@Data
public class BaseResponse<T> {
private String code;
private String message;
private T data;
/**
*
* 默认构造方法
*
* @param code
* 状态码
* @param message
* 接口信息
* @param data
* 接口数据
*/
public BaseResponse(String code, String message, T data) {
super();
this.code = code;
this.message = message;
this.data = data;
}
/**
* 默认构造方法
*/
public BaseResponse() {
super();
}
}
package com.swagger.demo.response;
public class RespGenerator {
/**
* 接口调用成功时出参
*
* @param data
* 接口返回数据
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static BaseResponse returnOK(Object data) {
return new BaseResponse("200", "接口调用成功!", data);
}
/**
* 调用失败
*
* @param code
* 错误码
* @param message
* 错误信息
* @return
*/
public static BaseResponse<Object> returnError(String code, String message) {
return new BaseResponse<Object>(code, message, null);
}
/**
* 调用失败
*
* @param message
* 错误信息
* @return
*/
public static BaseResponse<Object> returnError(String message) {
return new BaseResponse<Object>("-1", message, null);
}
}