本文共 3882 字,大约阅读时间需要 12 分钟。
现在的架构基本都由原来的后端渲染,变成了:前端渲染、前后端分离的形态,前端和后端唯一联系,变成了API接口;swagger就是一款让你更好的维护API文档的框架。
io.springfox springfox-swagger2 2.9.2 io.springfox springfox-swagger-ui 2.9.2
在application.yml 中加入
spring: swagger: enable: true
true表示启用,false表示关闭
package com.rabbits.learn.config;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.service.Contact;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket;import springfox.documentation.swagger2.annotations.EnableSwagger2;/** * @Description: Swagger2配置信息 * @Author: RabbitsInTheGrass_xj * @Date: 2019/10/4 10:36 */@EnableSwagger2@Configuration@ConditionalOnProperty(name = "spring.swagger.enable", havingValue = "true")public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(buildApiInf()) .select() //扫描的swagger接口包路径 .apis(RequestHandlerSelectors.basePackage("com.xj.demo.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo buildApiInf() { return new ApiInfoBuilder() //标题 .title("RabbitsInTheGrass的用Swagger2构建RESTful API文档") .description("更多SpringBoot相关文章请关注:https://blog.csdn.net/RabbitInTheGrass") .termsOfServiceUrl("https://blog.csdn.net/RabbitInTheGrass/article/details/102026732") //作者 .contact(new Contact("RabbitInTheGrass", "https://blog.csdn.net/RabbitInTheGrass", "xiqiyeyou@163.com")) //版本 .version("1.0") .build(); }}
@ConditionalOnProperty(name = “spring.swagger.enable”, havingValue = “true”)该注解标识@Configuration注解开启的条件。
name对应application.yml中的参数; havingValue表示条件值。启动类增加@EnableSwagger2的注释。
对应于HTTP协议中的方法注解:
package com.rabbits.learn.controller;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * @Description: 测试一下 * @Author: RabbitsInTheGrass_xj * @Date: 2019/10/1 09:31 */@RestController@RequestMapping("/home")@Api(value = "我的hello层")public class HomeController { @ApiOperation(value = "打招呼", notes = "开始的一个hello") @GetMapping("hello") public String sayHello() { return "Hello RabbitsInTheGrass, welcome!!!"; }}
启动项目后访问 http://localhost:8080/swagger-ui.html ,效果图如下: