springboot+swagger从看到自己动手配

这是一个swagger接口文档页面,至于swagger有什么好处我就不说了,网上一大堆,现在我记录一下怎么在springboot中配置swagger。

1.添加依赖,网上也有很多依赖的版本,现在我这个是比较新也比较主流的版本。

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>

2.添加一个Swagger2的配置类,随你怎么命名Swagger2Config/Swagger2都可以。需要注意的是类上面添加两个注解和@bean注解

@Configuration
@EnableSwagger2
public class Swagger2 {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //为controller包路径
                .apis(RequestHandlerSelectors.basePackage("org.common.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("使用Swagger2构建RESTful APIs")
                .description("admin swagger测试页面")
                .termsOfServiceUrl("")
                .contact("千山暮雪")
                .version("1.0")
                .build();
    }
}

其实这个格式和内容都是固定的,可以直接复制,但需要注意的是controller包的路径,一定要注意,千万别错了,我就是在这错了,偏偏自己还没有注意到。以前习惯的是com.xxx.xxx.controller,自己不相信踩了坑……

然后其他的对应的分别是这些内容

3.添加WebMvcConfig配置类,或者是在已有的该配置中添加

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/js/**").addResourceLocations("classpath:/js/");

        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }

}

直接复制即可,功能:在未登录的情况下通过在springboot的security安全机制的过滤器。

4.最后就是添加一个测试的controller

code:

@Api(description = "swagger测试接口")
@RestController
@RequestMapping("/demoController")
public class SwaggerDemoController {
    @ApiOperation(value = "s1" ,  notes="s2")
    @RequestMapping
    @GetMapping("/getTest")
    public String getTest(Integer i) {
        System.out.println("开始调用接口");
        return new Json("返回数据").toString()+ i;
    }
}

这就ok了,下一篇讲讲遇到的小问题,出现的小bug怎么解决。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值