1.整合依赖
<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>
2.项目配置(放入swagger.properties中)
swagger.title=swagger测试项目
swagger.description=swagger测试案例
swagger.version=1.0.0
3.创建工具类
package com.example.swagger2.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@PropertySource("classpath:swagger.properties")
@ConfigurationProperties("swagger")
@EnableSwagger2
public class SwaggerConfig {
private String title;
private String description;
private String version;
// 省略Getter/Setter
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any()).build();
}
public ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(this.title)
.description(this.description)
.version(this.version).build();
}
}
4.创建测试控制类
package com.example.swagger2.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@Api(tags = "测试类")
@RestController
@RequestMapping("/test")
public class TestController {
@ApiOperation("测试方法")
@GetMapping("/")
public String test(
@ApiParam(value = "入参", required = true)
@RequestParam String text) {
return text;
}
}
5.访问Swagger接口文档
http://localhost:8080/swagger-ui.html