您好,登录后才能下订单哦!
Spring boot配置 swagger的代码怎么写,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
在实际开发中我们作为后端总是给前端或者其他系统提供接口,每次写完代码之后不可避免的都需要去写接口文档,首先写接口文档是一件繁琐的事,其次由接口到接口文档需要对字段、甚至是排版等。再加上如果我们是为多个系统提供接口时可能还需要按照不同系统的要求去书写文档,那么有没有一种方式让我们在开发阶段就给前端提供好接口文档,甚至我们可以把生成好的接口文档暴露出去供其他系统调用,那么这样我只需要一份代码即可。
1.导入maven依赖
<!--配置swagger--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.6.1</version> </dependency> <!--swagger第三方ui--> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.9.6</version> </dependency>
2.swagger配置类
@EnableSwagger2                // Swagger的开关,表示已经启用Swagger
@Configuration                 // 声明当前配置类
public class SwaggerConfiguration  {
    @Value("${swagger.basePackage}")
    private String basePackage;       // controller接口所在的包
    @Value("${swagger.title}")
    private String title;           // 当前文档的标题
    @Value("${swagger.description}")
    private String description;         // 当前文档的详细描述
    @Value("${swagger.version}")
    private String version;         // 当前文档的版本
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(title)
                .description(description)
                .version(version)
                .build();
    }
}3.application.yml
# 配置swagger swagger: basePackage: com.xx.demo.controller #包名 title: 标题 #标题 description: 项目文档 #描述 version: V1.0 #版本号
4.在controller里使用
@Api(tags = {"测试类"})
@RestController
@RequestMapping("/test")
public class TestController {
    @ApiOperation(value = "测试方法")
    @GetMapping("/xrx")
    public String xrx() {
        return "hello";
    }
}5.访问swagger
http://localhost:8080/swagger-ui.html
http://localhost:8080/doc.html

关于Spring boot配置 swagger的代码怎么写问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。