《微服务之SpringBoot整合Swagger2》

前言:

       Swagger,中文“拽”的意思,它是一个功能强大的在线API文档的框架,目前它的版本为2.x,继而称为Swagger2.其提供了在线文档的查阅和测试功能。利用其很容易构建RESTful风格的API,在SpringBoot中集成Swagger2.

正文:

   一。引入依赖--springfox-swagger2和springfox-swagger-ui

       <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 --编写Swagger2

         在类的上方加上@Configuration注解,表明是一个配置类,@EnableSwagger2开启Swagger2功能。在配置类Swagger2需要注入一个Docket的Bean,该Bean包含了apiInfo,即基本API文档的描述信息以及包扫描的基本包名等信息

package com.example.hellojpa;

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


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

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot利用swagger构建api文档")
                .description("简单优雅的restful风格,http://blog.csdn.net/forezp")
                .version("1.0")
                .build();
    }
}

  三。写生成文档的注解

        Swagger2通过注解来生成API接口文档,文档信息包括 接口名、请求方法、参数、返回信息等。通常情况下用于生成在线API文档:

        @Api:修饰整个类,用于描述Controller类

        @ApiOperation:描述类的方法,或者说一个接口

        @ApiParam:单个参数描述

        @ApiProperty:用对象接收参数时,描述对象的一个字段。

        @ApiResponse:HTTP响应的一个描述

        @ApiResponses:HTTP响应的整体描述

        @ApiIgnore:使用该注解,表示Swagger2忽略这个API

        @ApiError:发生错误返回的信息

        @ApiParamImplicit:一个请求参数

        @ApiParamsImplicit:多个请求参数

   四。编写Service层代码

package com.example.hellojpa;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserService {
    @Autowired
    private UserDao userRepository;

    public User findUserByName(String username) {
        return userRepository.findByUsername(username);
    }

    public List<User> findAll() {
        return userRepository.findAll();
    }

    public User saveUser(User user) {
        return userRepository.save(user);
    }

    //做过改动
    public Optional<User> findUserById(long id) {
        return userRepository.findById(id);
    }

    public User updateUser(User user) {
        return userRepository.saveAndFlush(user);
    }

    //做过改动
    public void deleteUser(long id) {
        userRepository.deleteById(id);
    }
}

    五。Web层 

package com.example.hellojpa;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;
import java.util.Optional;

@RequestMapping(value = "/user")
@RestController
public class UserController {
    @Autowired
    UserService userService;

    @ApiOperation(value = "用户列表", notes = "用户列表")
    @RequestMapping(value = {" "}, method = RequestMethod.GET)
    public List<User> getUsers() {
        List<User> users = userService.findAll();
        return users;
    }

    @ApiOperation(value = "创建用户", notes = "创建用户")
    @RequestMapping(value = "", method = RequestMethod.POST)
    public User postUser(@RequestBody User user) {
        return userService.saveUser(user);
    }

    @ApiOperation(value = "获取用户信息", notes = "根据url的id来获取详细信息")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Optional<User> getUser(@PathVariable Long id) {
        return userService.findUserById(id);
    }

    @ApiOperation(value = "更新信息", notes = "根据url的id来指定更新用户信息")
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public User putUser(@PathVariable Long id, @RequestBody User user) {
        User user1 = new User();
        user1.setUsername(user.getUsername());
        user1.setPassword(user.getPassword());
        user1.setId(user.getId());
        return userService.updateUser(user1);
    }

    //value值为该接口的名称,notes值为该接口的详细文档说明
    @ApiOperation(value = "删除用户", notes = "根据url的id来指定删除用户")
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return "success";
    }

    @ApiIgnore //使用该注解忽略这个API
    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    public String jsonTest() {
        return "hi you";
    }

}

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

         出现一个问题:启动工程之后,访问Swagger,访问地址,出现如下情况:

        问题定位:swagger配置类中的扫描包没有写对:

        .apis(RequestHandlerSelectors.basePackage("com.example"))修改为:

        .apis(RequestHandlerSelectors.basePackage("com.example.hellojpa"))

结语:

        用自己的实力,索要自己的未来

猜你喜欢

转载自blog.csdn.net/yxf15732625262/article/details/81745794
今日推荐