<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
<version>3.0.0version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger-uiartifactId>
<version>2.9.2version>
dependency>
<dependency>
<groupId>com.github.xiaoymingroupId>
<artifactId>knife4j-spring-boot-starterartifactId>
<version>3.0.3version>
dependency>
第二步:编写Swagger配置文件
@Configuration
@EnableSwagger2 // 重要!
//@EnableWebMvc
@ComponentScan(basePackages = { "com.hc" }) // Swagger扫描的package
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()//选择哪些路径和API会生成document
//扫描指定包中的swagger注解
//.apis(RequestHandlerSelectors.basePackage("com.hc"))
//扫描所有有注解的api,用这种方式更灵活
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
//扫描所有的api(没有添加注解也可以扫描出来),用这种方式更直接
//.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
/**
* 这是匹配api的信息
*
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 大标题
.title("API接口文档")
// 描述
.description("API接口测试")
// 版本号
.version("1.0.0")
.termsOfServiceUrl("").license("").licenseUrl("").build();
}
}
第三步:修改applicationContext.xml
<context:annotation-config />
<bean class="com.hc.config.SwaggerConfig"/>
第四步:Controller代码:
@Api(tags = "部门管理", value = "部门接口")
@RestController
@RequestMapping("/dept")
public class DeptController {
@ApiResponse(message = "测试", code = 200)
@ApiOperation(value = "fun", notes = "测试方法fun", httpMethod = "GET")
@GetMapping("/fun")
public String fun() {
return "fun";
}
@PutMapping(value = "/v1/{dname}")
@ApiOperation(value = "修改部门信息", notes = "", httpMethod = "PUT")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true, dataType = "String", dataTypeClass = String.class),
@ApiImplicitParam(paramType = "query", name = "deptno", value = "部门ID", required = true, dataType = "Integer", dataTypeClass = Integer.class),
@ApiImplicitParam(paramType = "path", name = "dname", value = "部门名称", required = true, dataType = "String", dataTypeClass = String.class),
@ApiImplicitParam(paramType = "body", name = "dept", value = "用户实体", required = true, dataType = "Dept", dataTypeClass = Dept.class)
})
public String fun(@RequestParam(name = "deptno", value = "deptno", required = false) Integer deptno,
@PathVariable(value = "dname", required = true) String dname,
@RequestBody(required = true) Dept dept,
HttpServletRequest request) {
String token = request.getHeader("token");
return token + " " + deptno + " " + dname + " " + dept;
}
}
第五步:浏览器访问
官方UI
网址: http://localhost:8080/项目名称/swagger-ui.html
网址:http://localhost:8080/项目名称/doc.html#/home
第一步中,引入的springfox-swagger-ui的版本为2.9.2,如果改成3.0.0以上,发现官方UI访问不了,具体怎么解决,暂未找到解决方案,哪位同学如果解决了,肯请告知,感谢!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)