Spring boot 整合 Swagger

The introduction of dependence:

First introduced Swagger required dependency:

<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!-- 使用Swagger2最新版本2.9.2避免NumberFormatException错误要引入下列两个依赖 -->
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.21</version>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
            <version>1.5.21</version>
        </dependency>

Swagger configuration:

Create a new class in the arranged Swagger.java conf:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi(){
        return  new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.winstar.system.controller"))
                .paths(PathSelectors.regex("/.*"))
                .build();
    }
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("WinStar-Vehicle 电动车项目构建")
                .description("文档地址:https://www.cnblogs.com/xiaofanblog/")
                .termsOfServiceUrl("https://www.cnblogs.com/xiaofanblog/")
                .contact(new Contact("xiaofan","https://www.cnblogs.com/xiaofanblog/","[email protected]"))
                .version("v1.0")
                .build();
    }
}

These are the Swagger global configuration information, most of which need attention are the following:

Swagger generating API documentation by the scanning method is specified package at request class map , generated according to the mapping interface API documentation interfaces, so the key is configured to scan a good interface class address.

.apis (RequestHandlerSelectors.basePackage ( "com.winstar.system.controller") ) scan request mapper class package address. When generally used SpringMVC, we often based on the request should be mapped / controller / packag under e.

.paths (PathSelectors.regex ( "/.*") ) scanning request path, for example, you want Swagger to show all the / rest interface address (for example, at the beginning of REST / the Save ), is set regex ( "/ rest /. * ") , this * is to match all the children of requests. Here we configure the scanning of all requests.

View PathSelectors source category:

public class PathSelectors {
    private PathSelectors() {
        throw new UnsupportedOperationException();
    }

    public static Predicate<String> any() {
        return Predicates.alwaysTrue();
    }

    public static Predicate<String> none() {
        return Predicates.alwaysFalse();
    }

    public static Predicate<String> regex(final String pathRegex) {
        return new Predicate<String>() {
            public boolean apply(String input) {
                return input.matches(pathRegex);
            }
        };
    }

    public static Predicate<String> ant(final String antPattern) {
        return new Predicate<String>() {
            public boolean apply(String input) {
                AntPathMatcher matcher = new AntPathMatcher();
                return matcher.match(antPattern, input);
            }
        };
    }
}

It found support 4 in a manner in accordance with the path generated API documentation:

1. Any paths are generated; 2. no path generation; 3 regular matching path; 4.ant pattern matching.

We are arranged above the regular matching path, in accordance with regular standard, Swagger scanning corresponding API interface and generate documents.

Since it uses Swagger, it is bound to follow RESTful interface specification:

Write business code:

entity: 

A new entity in the entity class object User.java

@Entity 
@Data 
the @Table (name = "User" )
 public  class the User {
     / ** 
     * primary key ID 
     * / 
    @Id 
    @GeneratedValue 
    Private Integer ID; 

    / ** 
     * Name 
     * / 
    Private String name; 

    / ** 
     * Account 
     * / 
    Private String the Account; 

    / ** 
     * password 
     * / 
    @JsonIgnore 
    Private String password; 

    / ** 
     * salt 
     * / 
    @JsonIgnore 
    Private String salt; 

    / ** 
     * whether disabled 0: No; 1: Yes 
     * /
    private String forbidden;
}

Result:

Typically, the Controller returns the data should be encapsulated in a class result, the purpose is to ensure that all request return result has a fixed response format , such as: status code , status , return results . So we simply packaging a result class: R.java

/ ** 
 * returns the HTTP object models obtained 
 * @param <T>
  * / 
@Data 
@JsonInclude (JsonInclude.Include.NON_NULL) 
public  class R & lt <T> {
     / ** 
     * Status Code 
     * / 
    Private Integer code; 

    / ** 
     * message 
     * / 
    Private String MSG; 

    / ** 
     * specific data 
     * / 
    Private T data; 
}

controller:

Under control of the new controller class UserController.java, write CRUD common business scenarios:

@Slf4j
@RestController
@RequestMapping("/api/v1/sys")
@Api(value = "UserController",tags = {"用户管理"})
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 新增用户
     * @param userFrom
     * @param bindingResult
     * @return
     */
    @ApiOperation(value = "新增用户信息")
    @RequiresPermissions("sys:user:insert")
    @PostMapping("/saveUser")
    public R saveUser(@Valid @RequestBody UserFrom userFrom,
                      BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【新增用户】参数不正确:userFrom={}"+ userFrom);
            throw new SystemException(REnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
        }

        return userService.saveUser(userFrom);
    }


    /**
     * 查询用户列表
     * @param page
     * @param size
     * @param name
     * @return
     */
    @ApiOperation(value = "查询用户列表")
    @RequiresPermissions("sys:user:list")
    @GetMapping("/selectUserList")
    public R selectUserList(@RequestParam(value = "page", defaultValue = "0") Integer page,
                            @RequestParam(value = "size", defaultValue = "10") Integer size,
                            @RequestParam(value = "name",defaultValue = "") String name){

        PageRequest pageRequest = new PageRequest(page,size);
        return userService.selectUserList(name,pageRequest);

    @param
     */ **
    }
     * Query User Details id
     * @return
     */
    @ApiOperation(value = "查询用户详情")
    @RequiresPermissions("sys:user:detail")
    @GetMapping("/selectUserDetail")
    public R selectUserDetail(@RequestParam(value = "id",required = false) Integer id){

        Assert.isNull(id,"id不能为空");
        return userService.selectUserDetail(id);
    }

    /**
     * 更新用户
     * @param userFrom
     * @param bindingResult
     * @return
     */
    @ApiOperation(value = "更新用户信息")
    @RequiresPermissions("sys:user:update")
    @PutMapping("/updateUser")
    public R updateUser(@Valid @RequestBody UserFrom userFrom,
                        BindingResult bindingResult){

        Assert.isNull(userFrom.getId(),"id不能为空");

        if(bindingResult.hasErrors()){
            log.error("【更新用户】参数不正确:userFrom = {}"+ userFrom);
            throw new SystemException(REnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
        }

        return userService.updateUser(userFrom);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @ApiOperation(value = "删除用户信息")
    @RequiresPermissions("sys:user:delete")
    @DeleteMapping("/deleteUser/{id}")
    public R deleteUser(@PathVariable Integer id){
        return userService.delectUser(id);
    }
}

test:

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

 

 Specifically Swagger notes, please refer Swagger notes articles: https://www.cnblogs.com/xiaofanblog/p/11430267.html

Guess you like

Origin www.cnblogs.com/xiaofanblog/p/11430386.html