swagger2用于通过配置的方式生成接口文档
引入jar包
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.4.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.4.0</version> </dependency>
配置swagger2启动类
@Configuration @EnableSwagger2 public class Swagger2 { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() //为当前包路径 .apis(RequestHandlerSelectors.basePackage("com.example.learn.swagger2")) .paths(PathSelectors.any()) .build(); } //构建 api文档的详细信息函数,注意这里的注解引用的是哪个 private ApiInfo apiInfo() { return new ApiInfoBuilder() //页面标题 .title("Spring Boot 测试使用 Swagger2 构建RESTful API") //创建人 .contact(new Contact("MarryFeng", "http://www.baidu.com", "")) //版本号 .version("1.0") //描述 .description("API 描述") .build(); } }
配置实体类和controller
model:
@Data @AllArgsConstructor @NoArgsConstructor @ApiModel("用户") public class User { @ApiModelProperty("用户baseId") private Integer baseId; @ApiModelProperty("用户id") private String userId; @ApiModelProperty("用户名") private String username; @ApiModelProperty("密码") private String password; }
controller:
@RestController @RequestMapping("/api") @Api("swaggerDemoController测试api") public class SwaggerDemoController { @Autowired private UserService userService; private static final Logger logger= LoggerFactory.getLogger(SwaggerDemoController.class); @ApiOperation(value = "根据id查询用户", notes = "查询用户信息") @ApiImplicitParam(name = "id",value = "用户id",required = true) @RequestMapping(value = "/getuser",method = RequestMethod.GET) public User getUser(@PathVariable String id){ return userService.getUser(id); } }
访问路径:
http://localhost:8080/swagger-ui.html