Spring Boot教程
作者: 时海
SpringBoot集成Swagger

1、maven配置

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

2、Swagger 配置类

package com.example.boot;

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.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .title("Swagger Api测试")
                        .contact(new Contact("zhansan", "http://www.k6k4.com/", "xxx@xx.com"))
                        .version("1.0")
                        .description("API 描述")
                        .build())
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.boot")).paths(PathSelectors.any())
                .build();
    }


}

3、application.yml配置选项

swagger:
  enable: true

4、Controller配置

package com.example.boot;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
@Api("用户API")
public class UserController {
    @Autowired
    UserMapper userMapper;

    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "根据id查询用户", notes = "查询单个用户")
    @ApiImplicitParam(name = "id", value = "UserId", defaultValue = "1", paramType = "path",
            required = true, dataType = "int")
    public User getUser(@PathVariable("id") Integer id) {
        User user = userMapper.getUser(id);
        return user;
    }
}

5、测试

http://localhost:8080/swagger-ui.html

一个创业中的苦逼程序员
  • 回复
隐藏