Springboot使用swagger2

本文详细介绍如何在Spring Boot项目中集成Swagger2实现API文档自动生成。包括在POM文件中添加依赖、创建Swagger2配置类及在Controller中使用Swagger注解的方法。

十月一结束啦 又要开始新的码农生活
首先在POM中加入配置文件


<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>

然后
创建Swagger2配置类

@Configuration
@EnableSwagger2
public class swagger {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
                .apis(RequestHandlerSelectors.basePackage(("com.firstdian.web")))
                .paths(PathSelectors.any()).build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("测试swagger")
        .description("第一次测试swagger")
        .termsOfServiceUrl("").contact("wxr").build();
    }
}

select()创建一个重建器,用于定义一些控制器及其生成的文档中应包含某种方法。
apis()定义为包含的类(控制器和模型类)。
path()允许根据路径映射定义应包含其中的控制器的方法。
在启动类同级添加一个swagger(用于启动项目之后可以直接打開swagger,可不加)
在这里插入图片描述

@Configuration
public class IndexConfig {
    @EventListener({ApplicationReadyEvent.class})
    void applicationReadyEvent() {
        System.out.println("应用已经准备就绪 ... 启动浏览器");
        String url = "http://localhost:8089/swagger-ui.html";
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec("rundll32 url.dll,FileProtocolHandler " + url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

controller 编写样式
在这里插入图片描述

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "查看数据", notes = "查看数据")
    @ApiImplicitParam(name = "id", value = "用戶id", required = true)
    public User getUser(@PathVariable Long id) {
        return users.get(id);
    }

加油!!!

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值