spingboot

SpringBoot2.x整合swagger2

2020-05-18  本文已影响0人  小胖学编程

当我们开发完一个接口后。一般使用postman来测试接口。而若是使用swagger便可以直接去简单测试我们的接口。

1. 引入依赖

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </dependency>

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

        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.7.2</version>
        </dependency>

2. 增加配置

package com.tellme.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    //    https://blog.csdn.net/m0_37882063/article/details/89139457
//    springboot swagger No operations defined in spec!
    @Bean
    public Docket petApi() {
        //设置请求头以及请求头默认值
        List<Parameter> pars = new ArrayList<>();
        ParameterBuilder ticketPar3 = new ParameterBuilder();
        ticketPar3.name("email").description("邮箱信息")
                .defaultValue("name@example.com")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(false).build(); //header中的ticket参数非必填,传空也可以

        pars.add(ticketPar3.build());

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.tellme.controller")) //指定提供接口所在的基包
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(pars);
    }


    /**
     * 该套 API 说明,包含作者、简介、版本、host、服务URL
     *
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("demo api 说明")
                .contact(new Contact("allen", "null", "name@example.com"))
                .version("0.1")
                .termsOfServiceUrl("localhost:8080/demo1/")
                .description("demo api")
                .build();
    }

}

3. 在接口上使用注解

@Api(value = "TransactionController类", tags = {"测试事务的接口"})
@RestController
public class TransactionController {
    @Autowired
    private TestTransactionService testTransactionService;

    @Autowired
    private IAccount accountImpl;

    private UserT userT;


    {
        userT = new UserT();
//        userT.setId(100);
        userT.setUserName("小胖");
        userT.setAge(12);
        userT.setPassword("123");
    }

    @RequestMapping("/userT")
    public void insertUserT() {
        //没有被代理
        System.out.println(accountImpl.getClass());
        testTransactionService.noTransactionMethod(userT);
    }

    @ApiOperation("事务插入数据")
    @RequestMapping("/user")
    public String insertUser(HttpServletRequest request) {
        String email = request.getHeader("email");
        System.out.println("浏览器上送的email信息:" + email);
        System.out.println("浏览器上送的cookie中的user信息:" + getCookie(request, "user"));

        testTransactionService.transactionMethod(userT);
        return "success";
    }


    public static String getCookie(HttpServletRequest request, String cookieName) {

        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieName)) {
                    return cookie.getValue();
                }
            }
        }

        return null;
    }
}

一般来说:简单的标记只需要@Api(tags="") 和 @ApiOperation(value="",notes="")注解。

4. 直接发送请求:

请求对应的url:http://localhost:8083/swagger-ui.html

image.png

点击发送请求,服务器的响应结果:

浏览器上送的email信息:name@example.com
浏览器上送的cookie中的user信息:小胖学编程
2020-05-18 13:24:45,225 DEBUG [29357] [http-nio-8083-exec-1] [] (BaseJdbcLogger.java:145): ==>  Preparing: insert into user_t (id, user_name, password, age) values (?, ?, ?, ?) 
2020-05-18 13:24:45,250 DEBUG [29382] [http-nio-8083-exec-1] [] (BaseJdbcLogger.java:145): ==> Parameters: null, 小胖(String), 123(String), 12(Integer)
2020-05-18 13:24:45,257 DEBUG [29389] [http-nio-8083-exec-1] [] (BaseJdbcLogger.java:145): <==    Updates: 1
1.后置处理
2.后置处理

5. 注意点:

  1. 一般系统都有认证,若是包含swagger字符串的url都不应该被认证过滤器过滤。

  2. swagger若是发送cookie信息,需要下载谷歌的EditThisCookie插件。下载的攻略:谷歌浏览器如何离线安装插件包

推荐阅读

https://github.com/SpringForAll/spring-boot-starter-swagger

https://www.cnblogs.com/zhaopengcheng/p/8583659.html

swagger注解的更多用法

上一篇 下一篇

猜你喜欢

热点阅读