Home > Java > javaTutorial > body text

Share the introduction of Swagger2+validator

零下一度
Release: 2017-07-17 13:37:48
Original
2793 people have browsed it

Introduction:

Swagger is a RESTful API used to describe projects and documents.

The specification here defines a set of file formats required to describe an API. These files are used by Swagger-UI projects to display the API and Swagger-Codegen generated clients in different languages. Additional tools can also take advantage of the generated files, such as testing tools.

<br>

Swagger2:
Copy after login
@Configuration
@EnableSwagger2public class Swagger2
{
    @Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.dj.edi.web"))
                .paths(PathSelectors.any())
                .build();
    }private ApiInfo apiInfo() {return new ApiInfoBuilder()
                .title("EID 用户 CRUD")
                .description("EID 用户 CRUD")
                .version("1.0")
                .build();
    }

}
Copy after login
<span style="font-size: 18px"><strong>Application:<br></strong></span>
Copy after login
@SpringBootApplication
@Import(springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration.class)public class ComEdiOrderUserApplication
{public static void main(String[] args) {SpringApplication.run(ComEdiOrderUserApplication.class, args);}

}
Copy after login
UserApiController:
Copy after login
<br>
Copy after login
Copy after login
@RestController
@RequestMapping("/v1/user")public class UserApiController
{private static final Logger LOGGER = LoggerFactory.getLogger(UserApiController.class);

    @Autowiredprivate ClientUsersRepository repository;

    @ApiOperation(value = "获取所有用户数据")
    @RequestMapping(value = "/list", method = RequestMethod.GET)public ResponseEntity<List<ClientUsers>> getClientUsersList() {try {return ResponseEntity.ok(repository.findAll());
        } catch (Exception e) {
            LOGGER.info(" 获取所有用户数据异常 " + e.getMessage(), e);return ResponseEntity.status(500).body(null);
        }
    }

    @ApiOperation(value = "获取用户数据")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String", paramType = "path")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)public ResponseEntity<ClientUsers> getClientUsers(@PathVariable String id) {try {return ResponseEntity.ok(repository.findOne(id));
        } catch (Exception e) {
            LOGGER.info(" 获取用户数据  " + id + "  数据异常 " + e.getMessage(), e);return ResponseEntity.status(500).body(null);
        }
    }

    @ApiOperation(value = "创建用户", notes = "根据User对象创建用户")
    @ApiImplicitParam(name = "users", value = "用户详细实体user", required = true, dataType = "ClientUsers", paramType = "body")
    @RequestMapping(method = RequestMethod.POST)public ResponseEntity<ClientUsers> createUser(@Valid @RequestBody ClientUsers users) {try {

            users.setId(ObjectId.get().toString());return ResponseEntity.ok(repository.save(users));

        } catch (Exception e) {
            LOGGER.info(" 创建用户  " + users + "  数据异常 " + e.getMessage(), e);return ResponseEntity.status(500).body(null);
        }
    }

    @ApiOperation(value = "更新用户详细信息", notes = "根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "ClientUsers", paramType = "body")
    })
    @RequestMapping(value = "{id}", method = RequestMethod.PUT)public ResponseEntity<ClientUsers> updateUser(@PathVariable("id") String id,@Valid @RequestBody ClientUsers user) {try {
            user.setId(id);return ResponseEntity.ok(repository.save(user));
        } catch (Exception e) {
            LOGGER.info(" 更新用户  " + user + "  数据异常 " + e.getMessage(), e);return ResponseEntity.status(500).body(null);
        }
    }

    @ApiOperation(value = "删除用户", notes = "根据url的id来指定删除对象")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String", paramType = "path")
    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)public ResponseEntity<String> deleteUser(@PathVariable String id) {try {
            repository.delete(id);return ResponseEntity.ok("ok");
        } catch (Exception e) {
            LOGGER.info(" 删除用户  " + id + "  数据异常 " + e.getMessage(), e);return ResponseEntity.status(500).body(null);
        }
    }
}
Copy after login
<br>
Copy after login
Copy after login
ClientUsersRepository:<br>
Copy after login
@Componentpublic interface ClientUsersRepository extends MongoRepository<ClientUsers, String>{
    ClientUsers findByips(String ip);
    ClientUsers findByclientFlag(String clientFlag);
}
Copy after login
ClientUsers:<br>
Copy after login
@Datapublic class ClientUsers implements Serializable
{

    @Idprivate String id;/** * 用户名称     */@NotBlank(message = "用户名称 不能为空")
    @Pattern(regexp = "^(?!string)",message = "不能是 stirng")private String userName;/** * ip     */@NotNull(message = "ip 至少需要个")private List<String> ips;/** * 标识     */@NotBlank(message = " 标识 不能为空")
    @Pattern(regexp = "^(?!string)",message = "不能是 stirng")private String clientFlag;/** * 客户服务ID     */@NotBlank(message = "客户服务ID 不能为空")
    @Pattern(regexp = "^(?!string)",message = "不能是 stirng")private String checkID;
}
Copy after login

有哪里不好的希望指正
Copy after login
 <br>
Copy after login

The above is the detailed content of Share the introduction of Swagger2+validator. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template