SpringBoot + mybatis + Swagger快速构建REST API并生成优美的API文档

Spring Boot能够快速开发、便捷部署等特性,相信有很大一部分Spring Boot的用户会用来构建REST API。
我们构建RESTful API的目的通常都是由于多终端的原因,这些终端会共用很多底层业务逻辑,因此我们会抽象出这样一层来同时服务于多个移动端或者Web前端。这样一来,我们的RESTful API就有可能要面对多个开发人员或多个开发团队:IOS开发、Android开发或是Web开发等。为了减少与其他团队平时开发期间的频繁沟通成本,我们可以创建一份RESTful API文档来记录所有接口细节。

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。
Swagger UI允许任何人 - 无论是您的开发团队还是最终消费者 - 可视化并与API资源进行交互,而无需执行任何实施逻辑。它是从您的Swagger规范自动生成的,可视化文档使后端实现和客户端消耗变得容易。

git中项目的下载地址:https://gitee.com/ydn/springboot-mybatis-swagger


1、创建一个spring boot项目

在浏览器中输入start.spring.io进入快速自动创建spring boot的页面。填写对应的参数之后,点击生成,就生成了一个spring boot项目。把项目import到你的开发工具中即可(记住:是导入已存在的maven项目)。

SpringBoot + mybatis + Swagger快速构建REST API并生成优美的API文档_第1张图片

2、在pom.xml中新增所需的依赖项


<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-JavaartifactId>
    <version>5.1.6version>
dependency>


<dependency>
    <groupId>io.springfoxgroupId>
    <artifactId>springfox-swagger2artifactId>
    <version>2.2.2version>
dependency>
<dependency>
    <groupId>io.springfoxgroupId>
    <artifactId>springfox-swagger-uiartifactId>
    <version>2.2.2version>
dependency>


<dependency>
    <groupId>org.mybatis.spring.bootgroupId>
    <artifactId>mybatis-spring-boot-starterartifactId>
    <version>1.3.0version>
dependency>


<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-webartifactId>
dependency>


3、使用mybatis的genarator插件自动生成dao和entity实体类

具体方法参考这篇文章:http://blog.csdn.net/qq_36748278/article/details/78208830
数据库的sql文件我也放在我的git代码里面了,可以下载。https://gitee.com/ydn/springboot-mybatis-swagger


4、创建对应的service接口和servie实现类


5、创建对应Controller

下面贴出DepartmentController 来深刻理解:

@RestController
@RequestMapping(value = "dep")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    @ApiOperation("添加")
    @RequestMapping(value = "", method = RequestMethod.POST)
    private JsonResult add(@RequestBody Department department) {
        Integer row = departmentService.add(department);

        JsonResult jsonResult = new JsonResult();
        if (row > 0) {
            jsonResult.setResultCode(200);
            jsonResult.setResultName("success");
        }

        return jsonResult;
    }

    @ApiOperation("根据id删除信息")
    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
    private JsonResult delete(@PathVariable Integer id) { // 删除的时候不需要传递json数据,但是需要有参数id,因此用
                                                            // @PathVariable注解参数
        Integer row = departmentService.delete(id);

        JsonResult jsonResult = new JsonResult();
        if (row > 0) {
            jsonResult.setResultCode(200);
            jsonResult.setResultName("success");
        }

        return jsonResult;
    }

    @ApiOperation("根据id更新信息")
    @RequestMapping(value = "{id}", method = RequestMethod.PUT)
    private JsonResult update(@RequestBody Department department, @PathVariable Integer id) {
        Integer row = departmentService.update(department);

        JsonResult jsonResult = new JsonResult();
        if (row > 0) {
            jsonResult.setResultCode(200);
            jsonResult.setResultName("success");
        }

        return jsonResult;
    }

    @ApiOperation("根据id查询信息")
    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    private JsonResult queryById(@PathVariable Integer id) {
        Department department = departmentService.queryById(id);

        JsonResult jsonResult = new JsonResult();
        if (department != null) {
            jsonResult.setResultCode(200);
            jsonResult.setResultName("success");
            jsonResult.setResult(department);
        }

        return jsonResult;
    }

    @ApiOperation("查询所有")
    @RequestMapping(value = "", method = RequestMethod.GET)
    private JsonResult queryAll() {
        List departLists = departmentService.queryAll();

        JsonResult jsonResult = new JsonResult();
        if (departLists != null && departLists.size() > 0) {
            jsonResult.setResultCode(200);
            jsonResult.setResultName("success");
            jsonResult.setResult(departLists);
        }

        return jsonResult;
    }

}

REStful体现在哪里呢?

@RestController
@RequestMapping(value = "dep")
public class DepartmentController 

@ApiOperation("添加")
@RequestMapping(value = "", method = RequestMethod.POST)

@ApiOperation("根据id删除信息")
@RequestMapping(value = "{id}", method = RequestMethod.DELETE)

@ApiOperation("根据id更新信息")
@RequestMapping(value = "{id}", method = RequestMethod.PUT)

@ApiOperation("根据id查询信息")
@RequestMapping(value = "{id}", method = RequestMethod.GET)

@ApiOperation("查询所有")
@RequestMapping(value = "", method = RequestMethod.GET)

每个方法都有一个路径注解,通过method属性通过区分不通的请求方式来区分他是什么操作的。
甚至有的方法的请求路径是一摸一样的,比如根据id查询和根据id删除,他们的路径都是 http://localhost:8080/dep/1 (假设id是1的数据),但是查询是GET请求,而删除是DELETE请求,因此就可以区分不同的操作了。
也就是以一种严格的方式来规范编码。提供简明扼要的接口供各种端调用。

请求地址 请求方式 提交数据 实现功能
dep GET 查询所有
dep/1 GET 查询id为1的数据
dep/1 DELETE 删除id为1的数据
dep POST { “departname”:”研发部”} 删除id为1的数据
dep/1 PUT { “departname”:”产品部”} 修改id为1的数据


6、添加application.properties相关配置

spring.datasource.url=jdbc:mysql://localhost:3306/student?characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver


6、创建Swagger2配置类

package com.danni.config;

@Configuration                       //注解表示这个是一个配置文件,让spring来加载该类配置
@EnableSwagger2                      //注解表示启用Swagger2
public class SwaggerConfig {
    @Bean                            //注解表示交由bean容器去管理
    public Docket newsApi() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2);
        docket.enable(true);
        //apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。
        //select()函数返回一个ApiSelectorBuilder实例用来控制哪些接口暴露给Swagger来展现,本例采用指定扫描的包路径来定义,Swagger会扫描该包下所有Controller定义的API,并产生文档内容(除了被@ApiIgnore指定的请求)。
        docket.apiInfo(apiInfo())
              .select()
              .apis(RequestHandlerSelectors.basePackage("com.danni.web.controller"))   
              .paths(PathSelectors.any()).build();
        return docket;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("dali的项目").description("在这里你可以浏览项目所有接口,并提供相关测试工具")
                .termsOfServiceUrl("http://www-03.ibm.com/software/sla/sladb.nsf/sla/bm?Open").contact("test")
                .license("China Red Star Licence Version 1.0").licenseUrl("#").version("1.0").build();
    }

}


7、修改主配置文件

主文件的包名一定要是基本包名,不然他访问不到。我这里设置的是com.danni

@SpringBootApplication
@MapperScan(value = "com.danni.model.dao")        //自动扫描配置文件注解
public class SpringbootMybatisSwaggerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisSwaggerApplication.class, args);
    }
}


8、启动程序

启动程序(也就是application.java,它里面有main方法,是程序的入口),访问http://localhost:8080/swagger-ui.html页面

SpringBoot + mybatis + Swagger快速构建REST API并生成优美的API文档_第2张图片

9、跨域调用上面的服务接口

如果需要跨域调用上面的服务接口,比如你在你的前端页面中调用登录方法,这就是跨域请求,你的域名不同。因此就需要添加如下的配置文件。否则访问不了

//提供跨域访问的配置
@Configuration
public class CorsConfig {

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
        corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
        corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }
}

SpringBoot + mybatis + Swagger快速构建REST API并生成优美的API文档_第3张图片

你可能感兴趣的:(java框架)