1.pom.xml中引入依赖
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> </dependency>
方式一:Application.java中引入 @EnableSwagger2来启动swagger注解
@SpringBootApplication // 组件扫描 @EnableSwagger2 public class Application { }
方式二:创建Swagger2配置类
package com.fz.hr.config; import io.swagger.annotations.ApiOperation; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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 @EnableSwagger2 @ConditionalOnProperty(prefix = "hr", name = "swagger-open", havingValue = "true") public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) //这里采用包含注解的方式来确定要显示的接口 //.apis(RequestHandlerSelectors.basePackage("com.fz.hr.modules.system.controller")) //这里采用包扫描的方式来确定要显示的接口 .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("HR Doc") .description("HR Api文档") .contact("WH") .version("2.0") .build(); } }
如上代码所示,通过@Configuration
注解,让Spring来加载该类配置。
再通过@EnableSwagger2
注解来启用Swagger2。
再通过createRestApi
函数创建Docket
的Bean之后,apiInfo()
用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。
select()
函数返回一个ApiSelectorBuilder
实例用来控制哪些接口暴露给Swagger来展现,本例采用指定扫描的包路径来定义,
Swagger会扫描该包下所有Controller定义的API,并产生文档内容(除了被@ApiIgnore
指定的请求)
接口注解
@RestController
@RequestMapping("/user")
@Api("userController相关api")
public class UserController {
@Autowired
private UserService userService;
@ApiOperation("获取用户信息")
@ApiImplicitParams({
@ApiImplicitParam(paramType="header",name="username",dataType="String",required=true,value="用户的姓名",defaultValue="zhaojigang"),
@ApiImplicitParam(paramType="query",name="password",dataType="String",required=true,value="用户的密码",defaultValue="wangna")
})
@ApiResponses({
@ApiResponse(code=400,message="请求参数没填好"),
@ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})
@RequestMapping(value="/getUser",method=RequestMethod.GET)
public User getUser(@RequestHeader("username") String username, @RequestParam("password") String password) {
return userService.getUser(username,password);
}
}
访问地址:访问:http://localhost:8080/swagger-ui.html
参考:
https://swagger.io/