[java]构建在线restfulAPI文档之swagger2

来源:互联网 发布:云计算应用 编辑:程序博客网 时间:2024/05/17 10:55
springfox定义: Automated JSON API documentation for API's built with Spring http://springfox.io
1. IntroductionThe Springfox suite of java libraries are all about automating the generation of machine and human readable specifications for JSON APIs written using the spring family of projects. Springfox works by examining an application, once, at runtime to infer API semantics based on spring configurations, class structure and various compile time java Annotations.1.1. HistorySpringfox has evolved from a project originally created by Marty Pitt and was named swagger-springmvc. Much kudos goes to Marty.1.2. GoalsTo extend support for a number of the evolving standards targeted at JSON API specification and documentation such as: swagger, RAML and jsonapi.To extend support for spring technologies other than spring webmvcPhilosophically, we want to discourage using (swagger-core) annotations that are not material to the service description at runtime. For e.g. the jackson annotations should always trump or have more weight than @ApiModelProperty or for e.g. @NotNull or specifying @RequestParam#required should always win. Annotations are to to be used only to supplement documentation or override/tweak the resulting spec in cases where its not possible to infer service/schema characteristics.

Swagger2  是 springfox 下面的一个开源项目,地址: https://github.com/springfox/springfox

使用 Swagger2
1: 导入Swagger2核心库和Swagger2 UI库
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 --><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.6.1</version></dependency><!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui --><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.6.1</version>

2: 配置 Docket bean,交给spring 容器管理
  官方文档地址:http://springfox.github.io/springfox/docs/current/#development-environment

@Configuration@EnableSwagger2public class Config{


@Bean
  public Docket petApi() {    return new Docket(DocumentationType.SWAGGER_2)        .select()          .apis(RequestHandlerSelectors.any())          .paths(PathSelectors.any())          .build()        .pathMapping("/")        .directModelSubstitute(LocalDate.class,            String.class)        .genericModelSubstitutes(ResponseEntity.class)        .alternateTypeRules(            newRule(typeResolver.resolve(DeferredResult.class,                    typeResolver.resolve(ResponseEntity.class, WildcardType.class)),                typeResolver.resolve(WildcardType.class)))        .useDefaultResponseMessages(false)        .globalResponseMessage(RequestMethod.GET,            newArrayList(new ResponseMessageBuilder()                .code(500)                .message("500 message")                .responseModel(new ModelRef("Error"))                .build()))        .securitySchemes(newArrayList(apiKey()))        .securityContexts(newArrayList(securityContext()))        .enableUrlTemplating(true)        .globalOperationParameters(            newArrayList(new ParameterBuilder()                .name("someGlobalParameter")                .description("Description of someGlobalParameter")                .modelRef(new ModelRef("string"))                .parameterType("query")                .required(true)                .build()))        .tags(new Tag("Pet Service", "All apis relating to pets"))         .additionalModels(typeResolver.resolve(AdditionalModel.class))         ;  }


Configuration explained







编写User API 并使用注解
 @ApiOperation(value = "查询用户",notes = "用户列表查询")    @GetMapping    public SaveUserModel findUser(            @ApiParam(value = "用户状态 normal |not Normal", required = true)            @RequestParam(name="status", defaultValue="normal") String status) {        return new SaveUserModel("xiaoming","123445");    }    @ApiOperation(value = "创建用户",notes = "新增一个用户")    @PostMapping    public SaveUserModel findPetsByStatus( @RequestBody SaveUserModel model) {        return new SaveUserModel("xiaoming","123445");    }

访问http://localhost:8080/swagger-ui.html 并调用API






常用相关注解
@ApiParam#value()@ApiImplicitParam#value()@ApiModelProperty#value()@ApiOperation#value()@ApiOperation#notes()@RequestParam#defaultValue()@RequestHeader#defaultValue()



阅读全文
0 0
原创粉丝点击