代码改变世界

SpringBoot + swagger

2018-03-04 21:07  甘雨路  阅读(629)  评论(0编辑  收藏  举报

 

添加依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>wonder</groupId>
    <artifactId>skyRainbow</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>


        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <!--jsp 的依赖 START-->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <!--jsp 的依赖 END-->

        <!--swagger 的依赖 START-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
        </dependency>
        <!--swagger 的依赖 END-->

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

添加springboot启动文件和swagger配置文件(注意路径,要放在外层package下)

 

package lf;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication // SpingBoot 相关注解,等于@Configuration、@EnableAutoConfiguration、@ComponentScan三个注解一起的作用
public class SkyRainbowApplication {

    public static void main(String[] args) {
        /**
         * Spring boot 程序入口
         */
        SpringApplication.run(SkyRainbowApplication.class,args);
    }
}
package lf;

import io.swagger.annotations.Api;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.async.DeferredResult;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import static com.google.common.base.Predicates.or;
import static springfox.documentation.builders.PathSelectors.regex;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api_lf(){
        return  new Docket(DocumentationType.SWAGGER_2)
                .groupName("api_lf")
                .genericModelSubstitutes(DeferredResult.class)
                .useDefaultResponseMessages(false)
                .forCodeGeneration(false)
                .pathMapping("/")
                .select()
                .paths(or(regex("/lf/.*")))
                .build()
                .apiInfo(apiInfo());

    }

    /**
     *  构建api文档详细信息
     */
    private ApiInfo apiInfo() {
        ApiInfo apiInfo = new ApiInfo(
                "甘雨路 API",// 标题
                "API 描述说明",//描述
                "1.0",//版本
                "NO terms of service",
                "lf@qq.com",// 创建人
                "The Apache License, Version 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0.html"
        );
        return apiInfo;
    }



}

添加相关配置(添加src/main/resources/application.properties内容如下)

# 页面默认前缀目录
spring.mvc.view.prefix=/WEB-INF/jsp/
# 响应页面默认后缀
spring.mvc.view.suffix=.jsp

#swagger
modulePath=/lf

添加相关Java类

package lf.entity;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;

@Api(description = "用户实体类")
public class SRUser {

    /**
     *  @ApiModelProperty 属性说明
     * value–字段说明
     * name–重写属性名字
     * dataType–重写属性类型
     * required–是否必填
     * example–举例说明
     * hidden–隐藏
     */
    @ApiModelProperty("用户名")//描述注解
    private String username;

    @ApiModelProperty(value = "密码",example = "数字,字母,下划线组成")
    private String password;

    @ApiModelProperty(value = "邮箱",example = "lf@qq.com")
    private String email;

    @ApiModelProperty("编码")
    private String number;

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
package lf.entity.utils;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.util.Map;

/**
 * 详情Dto
 * @param <T>
 */
@ApiModel(description = "详情DTO")
public class CommonDTO<T>{

    @ApiModelProperty(value = "提示信息")
    private String msg;

    @ApiModelProperty(value = "0 代表无错误 1代表有错误")
    private Integer status;

    @ApiModelProperty(value = "总记录")
    private Integer total;

    @ApiModelProperty(value = "业务数据")
    private T data;

    @ApiModelProperty(value = "200 代表无错误 400代表有错误--->加入这个字段是原生需求")
    private Integer code;


    @ApiModelProperty(value = "当前页码")
    private Integer pageNo = 1;

    @ApiModelProperty(value = "当前页码,默认:10")
    private Integer pageSize = Integer.valueOf(10); // 页面大小,设置为“-1”表示不进行分页(分页无效)

    @ApiModelProperty(value = "总记录数")
    private long totalSize;// 总记录数,设置为“-1”表示不查询总数



    private Map<String,Object> DataMap;

    public CommonDTO(Integer status) {
        if (status == 0){
            this.status = status;
            this.code = 200;
            this.msg = "操作成功";
        }
        this.data = null;
    }




    public CommonDTO(Integer status, Integer total) {
        if (status == 0){
            this.status = status;
            this.code = 200;
            this.msg = "操作成功";
        }
        this.data = null;
        this.total = total;
    }

    public Map<String, Object> getDataMap() {
        return DataMap;
    }

    public void setDataMap(Map<String, Object> dataMap) {
        DataMap = dataMap;
    }

    public Integer getCode() {return code;}

    public void setCode(Integer code) {this.code = code;}

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }


    public Integer getPageNo() {
        return (pageNo!=null&&pageNo>0)?pageNo:-1;
    }

    public void setPageNo(Integer pageNo) {
        this.pageNo = pageNo;
    }

    public Integer getPageSize() {
        return (pageSize!=null&&pageSize>0)?pageSize:10;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }


    /**
     * 获取设置总数
     * @return
     */
    public long getTotalSize() {
        return totalSize;
    }

    /**
     * 设置数据总数
     * @param count
     */
    public void setTotalSize(long totalSize) {
        this.totalSize = totalSize;
        if (pageSize >= totalSize){
            pageNo = 1;
        }
    }


    @Override
    public String toString() {
        return "CommonDTO{" +
                "msg='" + msg + '\'' +
                ", status=" + status +
                ", total=" + total +
                ", data=" + data +
                '}';
    }
}
package lf.controller;

import io.swagger.annotations.*;
import lf.entity.SRUser;
import lf.entity.utils.CommonDTO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Api(description = "用户控制器")//swagger注解用于类
@Controller // 控制器注解
@RequestMapping(value="${modulePath}/user")
public class UserController {

    /**
     * 获取用户信息
     */
    //@ApiOperation()用于方法;表示一个http请求的操作
    @ApiOperation(value = "用户信息接口",
            notes = "获取用户信息接口",
            position = 0)
    //@ApiResponses 响应集配置
    @ApiResponses(value = {@ApiResponse(code = 100, message = "用户信息接口异常"),
            @ApiResponse(code = 200, message = "用户信息接口成功")})
    @ResponseBody // 返回json数据的注解
    @RequestMapping(value = "/info",method = RequestMethod.GET)
    public CommonDTO<SRUser> getUserInfo(@ApiParam("用户编码") SRUser user){
        CommonDTO<SRUser> detailDTO = new CommonDTO<>(0,1);
        try {
            //SRUser user = new SRUser();
            user.setUsername("甘雨路");
            user.setPassword("123456");
            user.setEmail("1498222322@qq.com");
            detailDTO.setData(user);
        } catch (Exception e) {
            e.printStackTrace();
            detailDTO.setStatus(1);
            detailDTO.setCode(400);
            detailDTO.setMsg("获取用户信息异常:"+e.getMessage());

        }

        return detailDTO;
    }

}

启动程序,在浏览器上输入http://localhost:8080/swagger-ui.html,即可