1、添加依赖
依赖说明:springboot版本不能过低
org.springframework.boot
spring-boot-starter-parent
2.4.3
<!--swagger-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.2</version>
</dependency>
或者/下边需要在配置上加@EnableSwaggerBootstrapUI
controller需要加标签
@Api(tags = {"用户管理"}, description = "用户管理")
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!--swagger-->
2、swagger2配置类
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket defaultApi2() {
Docket docket=new Docket(DocumentationType.SWAGGER_2)
//线上关闭swagger
.enable(true)
.apiInfo(new ApiInfoBuilder()
.title("测试swagger2")
.description("<div style='font-size:14px;color:red;'>测试</div>")
.termsOfServiceUrl("")
.version("1.0")
.build())
.select()
//这里指定Controller扫描包路径
.apis(RequestHandlerSelectors.basePackage("com.qxwb"))
.paths(PathSelectors.any())
.build();
return docket;
}
}
3、项目name
server:
port: 8080
servlet:
context-path: /test
4、测试controller
@Slf4j
@RestController
@RequestMapping("/customerAttributes")
@Api(value = "客户属性表API", tags = {"客户属性表"})
public class TestController {
@PostMapping("/add")
@ApiOperation("测试swagger")
public void addCustomerAttributes() throws Exception {
}
}
扩展:
增加header全局参数
/**
* 添加head参数配置
*/
private List getParameterList() {
ParameterBuilder clientIdTicket = new ParameterBuilder();
List pars = new ArrayList();
clientIdTicket.name(Constant.TOKEN_HERDER_KEY).description(“token令牌”)
.modelRef(new ModelRef(“string”))
.parameterType(“header”)
.required(false).build(); //设置false,表示clientId参数 非必填,可传可不传!
pars.add(clientIdTicket.build());
return pars;
}