Spring Boot中使用Swagger2

pom.xml中添加Swagger2依赖

2.6.1版本是16年11月才更新的版本

<!--引入Swagger2的依赖-->
        <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>

创建Swagger2配置类

(1)@Configuration注解,让Spring来加载该类配置。
(2)@EnableSwagger2注解来启用Swagger2。
 (3)apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。
(4)RequestHandlerSelectors.basePackage()中填的是你controller的目录
(5)apiInfo()方法中termsOfServiceUrlcontact可以用Contact的对象代替
(6)Swagger2已经不支持String类型的contact

Contact对象中name表示作者,url通常作为项目的链接,代替之前的termsOfServiceUrl方法,email的话不用我多说了吧,不想写的话可以为空字符串

(7)Docket类的方法:

    ①: Docket groupName(String var):设置栏目名

    ②: Docket apiInfo(ApiInfo apiInfo):设置文档信息

    ③: Docket pathMapping(String path):设置api根路径

    ④: Docket protocols(Set<String> protocols):设置协议,Sets为com.goolge.common下的类,Sets.newHashSet("https","http")相当于new HashSet(){{add("https");add("http");}};

    ⑤: ApiSelectorBuilder select():初始化并返回一个API选择构造器

(8)ApiSelectorBuilder类的方法:

    ①:  ApiSelectorBuilder apis(Predicate<RequestHandler> selector):添加选择条件并返回添加后的ApiSelectorBuilder对象

   ②: ApiSelectorBuilder paths(Predicate<String> selector):设置路径筛选,该方法中含一句pathSelector = and(pathSelector, selector);表明条件为相与

(9)RequestHandlerSelectors类的方法:

    ①:  Predicate<RequestHandler> any():返回包含所有满足条件的请求处理器的断言,该断言总为true

    ②:  Predicate<RequestHandler> none():返回不满足条件的请求处理器的断言,该断言总为false

    ③:  Predicate<RequestHandler> basePackage(final String basePackage):返回一个断言(Predicate),该断言包含所有匹配basePackage下所有类的请求路径的请求处理器

(10)PathSelectors类的方法:

     ①:  Predicate<String> any():满足条件的路径,该断言总为true

     ②:  Predicate<String> none():不满足条件的路径,该断言总为false

     ③:  Predicate<String> regex(final String pathRegex):符合正则的路径

@Bean
    public Docket normalUserDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("普通用户API文档")
                .apiInfo(apiInfo("提供普通用户接口"))
                .protocols(Sets.newHashSet("https","http"))
                .produces(Sets.newHashSet("html/text"))
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("pers.graduation.controller.candidate"))//设置生成的Docket对应的Controller为candidate下的所有Controller
                .paths(PathSelectors.any())
                .build();
    }

createRestApi函数创建Docket的Bean之后,apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。select()函数返回一个ApiSelectorBuilder实例用来控制哪些接口暴露给Swagger来展现,采用指定扫描的包路径来定义,Swagger会扫描该包下所有Controller定义的API,并产生文档内容(除了被@ApiIgnore指定的请求)。

@Configuration
@EnableSwagger2
public class Swagger2 {
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.pjb.controller"))
                    .paths(PathSelectors.any())
                    .build();
        }
    private ApiInfo apiInfo() {
        Contact contact=new Contact("作者名",
          "http://www.jianshu.com/u/f192766abeab","email地址");
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2")
                .description("Hello Swagger2")
                //.termsOfServiceUrl("http://www.jianshu.com/u/f192766abeab")
                //.contact("作者名")
                .contact(contact)
                .version("1.0")
                .build();
    }
}

然后通过创建实体类和controller来简单测试下
具体的可以参照

简书作者 程序猿DD的文章Spring Boot中使用Swagger2构建强大的RESTful API文档

http://www.jianshu.com/p/8033ef83a8ed

注意

记得在UserController中需要id输入的方法的注解少了个参数配置: paramType="path",不然所有的参数类型都会是body,获取不到请求参数。例如
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long",paramType = "path")

访问:http://localhost:8080/swagger-ui.html
就能看到前文所展示的RESTful API的页面。

Paste_Image.png

选中所写的UserController后出现5个方法让你测试

添加文档内容

在完成了上述配置后,其实已经可以生产文档内容,但是这样的文档主要针对请求本身,而描述主要来源于函数等命名产生,对用户并不友好,我们通常需要自己增加一些说明来丰富文档内容。如下所示,我们通过@ApiOperation注解来给API增加说明、通过@ApiImplicitParams@ApiImplicitParam注解来给参数增加说明。


@RestController
@RequestMapping(value="/users")     // 通过这里配置使下面的映射都在/users下,可去除
public class UserController {

    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());

    @ApiOperation(value="获取用户列表", notes="")
    @RequestMapping(value={""}, method=RequestMethod.GET)
    public List<User> getUserList() {
        List<User> r = new ArrayList<User>(users.values());
        return r;
    }

    @ApiOperation(value="创建用户", notes="根据User对象创建用户")
    @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    @RequestMapping(value="", method=RequestMethod.POST)
    public String postUser(@RequestBody User user) {
        users.put(user.getId(), user);
        return "success";
    }

    @ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public User getUser(@PathVariable Long id) {
        return users.get(id);
    }

    @ApiOperation(value="更新用户详细信息", notes="根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    })
    @RequestMapping(value="/{id}", method=RequestMethod.PUT)
    public String putUser(@PathVariable Long id, @RequestBody User user) {
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id, u);
        return "success";
    }

    @ApiOperation(value="删除用户", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id) {
        users.remove(id);
        return "success";
    }

}

详细可参见官方文档:(LH) https://swagger.io/resources/articles/documenting-apis-with-swagger/

猜你喜欢

转载自blog.csdn.net/qq_36826506/article/details/82114545