springboot swagger-ui结合

随着移动互联的发展,前后端的分离已经是趋势。前后端已不是传统部门的划分,而是它们各有一套的生态系统,包括不同的开发语言、不同的开发流程、构建方式、测试流程等。做前端的不需要会maven作为构建工具,后端的也不需要准备grunt或gulp的构建工具。前后端只需要通过一定规则的接口来协作,数据交互的方式可以是json或xml等。前端只着重于数据的呈现,后端只负责数据提供及计算,前后端就会变得独立松耦合。使用文档来沟通时,也会遇到很大瓶颈问题,比如接口随着业务的发展,可能会多次更改,文档有可能会滞后,导致前后端开发风险增加。

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务,使整个API生命周期的开发,从设计和文档,到测试和部署。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。

一、添加依赖pom.xml

  <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
            <exclusions>
                <exclusion>
                    <groupId>com.fasterxml.jackson.core</groupId>
                    <artifactId>jackson-annotations</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>

二、java 配置注入

@Configuration
@EnableSwagger2
public class SwaggerConfig  extends WebMvcConfigurerAdapter {    
    @Bean
    public Docket api() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2);
        ApiInfo apiInfo = new ApiInfoBuilder().title("售后服务系统API").description("向售后服务系统提供服务接口")
                .version("v2.0").termsOfServiceUrl("www.domain.com")
                .contact(new Contact("张三", "www.domain.com", "email")).build();        
        docket.apiInfo(apiInfo);
        docket.enable(true);//设置是否可请求访问
        docket.select()
        .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))//设置那些类可供外面查看
        .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))////设置那些方法可供外面查看
        .build();
        return docket;
    }    
}

三、controller写法

@Api(value="用户相关接口")
@RestController
public class HomeController {    
    @ApiOperation(value="登录接口")
    @ApiImplicitParams(value={
            @ApiImplicitParam(name="account",value="帐号",paramType="query",required=true),
            @ApiImplicitParam(name="password",value="密码",paramType="query",required=true),
    })
    @ApiResponses(value={
            @ApiResponse(code=400,message="帐号不能为空"),
            @ApiResponse(code=401,message="密码不能为空"),
            @ApiResponse(code=500,message="帐号或密码错误"),
            @ApiResponse(code=200,message="成功",response=String.class)
    })
    @PostMapping("login")//默认显示七种请求方式
    public String login(String account, String password){
        
        return "";
    }

}

四、浏览访问http://localhost:9090/swagger-ui.html

try it out这是一个测试入口。

requestMapping若不指明那种httpMethod,会显示全部类型。

原文地址:https://www.cnblogs.com/song27/p/7543046.html