springboot integrated use of Swagger2

Swagger2 advantages compared to the traditional Api document

Api several handwritten document pain points:

Documentation needs to be updated, need to send a copy to the front again, that is not timely exchange of documentation updates.
Interface returns the result is not clear
can not be directly online test interface, usually requires the use of tools, such as the postman
too many interface documentation, poor management
Swagger is to solve this problem, of course, can not say that Swagger will certainly be perfect, of course, also has drawbacks, the most notably the code into relatively strong.
Swagger editor can be used as an interface written document, we explain here is SpringBoot integration Swagger2, direct way to generate interface documentation.
Dependent files

<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>

Configuration class

package com.boss.hr.train.fishkkmybatis.config;

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;

/**
 * @author fishkk
 * @version 1.0.0
 * @since
 */
@Configuration
public class Swagger2Configuration {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.boss.hr.train.fishkkmybatis.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot利用swagger构建api文档")
                .description("fishkk的Swagger")
                .version("1.0")
                .build();
    }

}

In the startup function a high price @ EnableSwagger2, here you can normally use the Swagger2

Swagger2 specific use
package com.boss.hr.train.fishkkmybatis.controller;

import com.boss.hr.train.fishkkmybatis.annotation.Logg;
import com.boss.hr.train.fishkkmybatis.entity.Dictionary;
import com.boss.hr.train.fishkkmybatis.entity.Result;
import com.boss.hr.train.fishkkmybatis.enums.DictionaryEnum;
import com.boss.hr.train.fishkkmybatis.exception.BaseException;
import com.boss.hr.train.fishkkmybatis.service.impl.DictionaryServiceImpl;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author fishkk
 * @version 1.0.0
 * @since 2019/7/27
 */
@RestController
@RequestMapping(value = "/dic")
@CrossOrigin
public class DictionaryController {
    /**
     * Redis 缓存
     */
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private DictionaryServiceImpl dictionaryService;

    private List<Dictionary> list;

    /**
     *  创建字典实体
     * @author fishkk
     * @since  2017/7/25
     * @param  dictionary 字典实体
     * @return  Dictionary 放回创建的字典实体
     */
    @ApiOperation(value="创建字典", notes="根据Dictionary对象创建字典")
    @ApiImplicitParam(name = "dictionary", value = "字典详细实体dictionary", required = true, dataType = "Dictionary")
    @PostMapping(value = "/insert")
    public Result insertDic(@Valid Dictionary dictionary, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return Result.error(DictionaryEnum.ERROR_INPUT);
        }
        dictionaryService.insert(dictionary);
        return Result.success(dictionary);
    }

    /**
     *  根据主键查找字典
     * @author fishkk
     * @since  2019/7/25
     * @param  id 主键id
     * @return dictionary查找到的实体对象
     */
    @ApiOperation(value = "获取字典信息",notes = "根据id获取字典信息")
    @ApiImplicitParam(name = "id",value = "字典id",required = true, dataType = "Long", paramType = "path")
    @GetMapping(value = "/dic")
    public Result findById(@RequestParam(value = "id") Integer id){
        if (list == null){
            list = dictionaryService.selectAll();
            for (Dictionary x:list) {
                long time = new Random().nextInt(10);
                redisTemplate.opsForValue().set(x.getCategoryId(),x,12,TimeUnit.HOURS);
            }
        }
        if (redisTemplate.opsForValue().get(id) != null){
            return Result.success(redisTemplate.opsForValue().get(id));
        }
        redisTemplate.opsForValue().set(id,dictionaryService.selectByPrimaryKey(id),12,TimeUnit.HOURS);
        return Result.success(dictionaryService.selectByPrimaryKey(id));

    }

    /**
     * 根据主键删除字典
     * @author fishkk
     * @since  2019/7/25
     * @param  id 字典主键
     */
    @ApiOperation(value = "根据id删除单个字典表",notes = "根据id删除字典")
    @ApiImplicitParam(name = "id",value = "用户id",required = true, dataType = "Long", paramType = "path")
    @GetMapping(value = "/remove/{id}")
    public Result deleteById(@PathVariable("id") Integer id){
        dictionaryService.deleteByPrimaryKey(id);
        return Result.success(null);
    }

    /**
     *  更新字典对象
     * @author fishkk
     * @since  2019/7/26
     * @param  dictionary 修改过的字典对象
     */
    @ApiOperation(value="更新字典", notes="根据Dictionary更新对应的字典")
    @ApiImplicitParam(name = "dictionary", value = "字典详细实体dictionary", required = true, dataType = "Dictionary")
    @PostMapping(value = "/updata")
    public Result updata(@Valid Dictionary dictionary, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return Result.error(DictionaryEnum.ERROR_INPUT);
        }
        dictionaryService.updateByPrimaryKey(dictionary);
        return Result.success(null);
    }

    /**
      *  根据字典名查询
      * @author fishkk
      * @since  2019/7/28
      * @param  name 字典名
      */
    @GetMapping(value = "/get/{name}")
    public Result findByName(@PathVariable("name") String name ){
        return Result.success(dictionaryService.findByName(name));
    }

    /**
     *  根据字典类型查询
     * @author fishkk
     * @since  2019/7/28
     * @param type 字典类型
     */
    @GetMapping(value = "/gettype/{type}")
    public Result findByType(@PathVariable("type") String type){
        return Result.success(dictionaryService.findByType(type));
    }

    /**
     *  获取全部对象
     * @author fishkk
     * @since  2019/7/28
     */
    @Logg
    @GetMapping(value = "/getall")
    public Result findByType(){
        //throw new BaseException(DictionaryEnum.NOT_FOUND);
      return Result.success(dictionaryService.selectAll());
//        Float a = null;
//        Float b = Float.intBitsToFloat(11);
//        System.out.println(a + b);
//        return null;
    }
}

Start SpringBoot project, visit http: // localhost: 8080 / swagger-ui.html

You can see a similar outcome of the appeal, I started the project too much trouble with SpringCloud not show.

Swagger2 comments

swagger through annotation indicates that this interface will generate documentation, including interface name, request methods, parameters, return information, and so on.

  • @Api: modification of the entire class, describe the role of Controller
  • @ApiOperation: describes a method of a class or an interface
  • @ApiParam: single parameter Description
  • @ApiModel: receiving the object parameters
  • @ApiProperty: Upon receiving the object parameters, a description of the object field
  • @ApiResponse: HTTP response is described wherein a
  • @ApiResponses: HTTP response Overall description
  • @ApiIgnore: use the API to ignore this comment
  • @ApiError: Error returned occur
  • @ApiImplicitParam: a request parameter
  • @ApiImplicitParams: a plurality of request parameters

Guess you like

Origin www.cnblogs.com/fishkk/p/11374642.html