API文档工具——Swagger

1.Swagger概念

  a.描述:Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务

  b.作用:

    1)接口的文档在线自动生成

    2)功能测试

  c.注解:

    1)@ApiModel:用于类,表示对类进行说明,用于参数用实体类接收

      ·value:表示对象名

      ·description:描述

    2)@ApiModelProperty:用于方法,字段;表示对model属性的说明或者数据操作更改

      ·value:字段说明

      ·name:重写属性名字

      ·dataType:重写属性类型

      ·required:是否必填

      ·example:举例说明

      ·hidden:隐藏

    3)@Api:修饰整个类,描述Controller的作用

      ·tags:控制类功能说明,tags是一个字符串数组,可以添加多个标签

      ·value:也是说明,可以使用tags替代

    4)@ApiOperation:描述一个类的一个方法,或者说一个接口

      ·value:用于方法描述

      ·notes:用于提示内容

      ·tags:可以重新分组

    5)@ApiParam:单个参数描述

      ·name:参数名

      ·value:参数说明

      ·required:是否必填

    6)@ApiImplicitParams、@ApiImplicitParam:用于方法,描述方法的参数(@ApiImplicitParams包含多个@AplimplicitParam)

      ·name:参数名

      ·value:参数说明

      ·dataType:数据类型

      ·paramType:参数类型

      ·example:举例说明

    7)@ApiIgnore:用于类或者方法上,可以不被swagger显示在页面上

 

2.Spring整合Swagger

  a.在数据库创建`t_user`用户表

-- 用户表
CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) NOT NULL,
  `user_pwd` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
);

 

  b.导入maven依赖

  <properties>

      ......

      <!-- spring -->
      <spring.version>5.1.1.RELEASE</spring.version>
      <!-- jackson-json -->
      <jackson.version>2.9.4</jackson.version>
      <!-- log4j -->
      <slf4j.version>1.7.18</slf4j.version>
      <log4j.version>1.2.17</log4j.version>
  </properties>

  <dependencies>
      <!-- spring -->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-oxm</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context-support</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>${spring.version}</version>
      </dependency>

      <!-- Jackson -->
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
          <version>${jackson.version}</version>
      </dependency>
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>${jackson.version}</version>
      </dependency>
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-annotations</artifactId>
          <version>${jackson.version}</version>
      </dependency>

      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
          <scope>test</scope>
      </dependency>

      <!-- AOP -->
      <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjrt</artifactId>
          <version>1.8.6</version>
      </dependency>
      <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjweaver</artifactId>
          <version>1.8.6</version>
      </dependency>

      <!-- 日志相关 -->
      <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>${log4j.version}</version>
      </dependency>
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>${slf4j.version}</version>
      </dependency>
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>${slf4j.version}</version>
      </dependency>

      <!-- servlet -->
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>4.0.1</version>
          <scope>provided</scope>
      </dependency>
      <dependency>
          <groupId>javax.servlet.jsp</groupId>
          <artifactId>jsp-api</artifactId>
          <version>2.2</version>
          <scope>provided</scope>
      </dependency>

      <!-- spring-jdbc -->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <!-- MySQL -->
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>8.0.13</version>
      </dependency>
      <!-- 连接池 -->
      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid</artifactId>
          <version>1.1.12</version>
      </dependency>

      <!-- mp 依赖 -->
      <dependency>
          <groupId>com.baomidou</groupId>
          <artifactId>mybatis-plus</artifactId>
          <version>3.2.0</version>
      </dependency>

      <!-- swagger -->
      <dependency>
          <groupId>io.springfox</groupId>
          <artifactId>springfox-swagger2</artifactId>
          <version>2.7.0</version>
      </dependency>
      <dependency>
          <groupId>io.springfox</groupId>
          <artifactId>springfox-swagger-ui</artifactId>
          <version>2.7.0</version>
      </dependency>
  </dependencies>

 

  2.创建 spring.xml 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 自动扫描的包名 -->
    <context:component-scan base-package="com.wode" />

    <!-- 开启AOP代理 -->
    <aop:aspectj-autoproxy proxy-target-class="true" />

    <!--开启注解处理器 -->
    <context:annotation-config />

    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!-- Spring中引入其他配置文件 -->
    <import resource="classpath*:/spring-mybatis.xml" />

</beans>

 

  3.创建 spring-mybatis.xml 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    <!-- 开启注解声明式事务 -->
    <tx:annotation-driven/>

    <!-- 数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!-- mybatits-plus 整合 Spring -->
    <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
        <!-- 加载数据源 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 指定 pojo 目录 -->
        <property name="typeAliasesPackage" value="com.wode.entity"/>
        <!-- mybatis-plus 插件 -->
        <property name="plugins">
            <array>
                <!-- 分页插件 -->
                <bean class="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"></bean>
            </array>
        </property>
        <!-- 加载 mybatis-plus 全局属性 -->
        <property name="globalConfig" ref="globalConfig" />
    </bean>

    <!-- 配置和 mybatis-plus 全局属性 -->
    <bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
        <property name="dbConfig" ref="dbConfig"/>
    </bean>
    <bean id="dbConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig.DbConfig">
        <!--
             AUTO -> 数据库ID自增
             INPUT -> 用户输入ID
             ID_WORKER -> 全局唯一ID
             UUID -> 全局唯一ID
          -->
        <property name="idType" value="AUTO"/>
        <!-- 全局的表前缀策略配置 -->
        <property name="tablePrefix" value="t_" />
    </bean>

    <!-- mybatis 的动态代理 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.wode.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

    <!-- 事务代理管理器 -->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>

 

  4.创建 jdbc.properties 配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mytest?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456

 

  5.创建 spring-mvc.xml 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <!-- 开启SpringMVC注解模式 -->
    <mvc:annotation-driven />

    <!-- 扫描web相关的bean -->
    <context:component-scan base-package="com.wode.controller" />

    <!-- 静态资源默认servlet配置 -->
    <mvc:default-servlet-handler/>

    <!-- swagger配置类 -->
    <bean class="com.wode.config.SwaggerConfig" />

    <!-- 配置jsp 显示ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/page/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

 

  6.配置 web.xml 配置文件

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!-- 欢迎界面 -->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <!-- 加载Spring配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml</param-value>
  </context-param>

  <!-- SpringMvc监听Spring配置 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!-- 通过xml加载SpringMvc的DispatcherServlet -->
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!-- 编码过滤器 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>
      org.springframework.web.filter.CharacterEncodingFilter
    </filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

 

  7.创建Swagger配置类

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("对外开放接口API 文档")               //大标题 title
                .description("HTTP对外开放接口")             //小标题
                .version("1.0.0")                           //版本
                .termsOfServiceUrl("http://xxx.xxx.com")    //终端服务程序
                .license("LICENSE")                         //链接显示文字
                .licenseUrl("http://xxx.xxx.com")           //网站链接
                .build();
    }

}

 

  8.创建Entity实体类

@ApiModel("用户") //@ApiModel用于类,表示对类进行说明,用于参数用实体类接收
@TableName
//@TableName("t_user")
public class User {

    @ApiModelProperty(value="用户ID") //@ApiModelProperty用于方法,字段;表示对model属性的说明或者数据操作更改
    @TableId
    private int id;
    @ApiModelProperty(value="用户名", required=true)
    private String userName;
    @ApiModelProperty(value="密码", required=true)
    private String userPwd;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPwd() {
        return userPwd;
    }

    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }
}

 

  9.创建DAO

public interface UserMapper extends BaseMapper<User> {
}

 

  10.创建Service

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    public boolean addUser(User user){
        if(userMapper.insert(user) > 0){
            return true;
        }
        return false;
    }

    public boolean updateUser(User user){
        if(userMapper.updateById(user) > 0){
            return true;
        }
        return false;
    }

    public User getUser(int id){
        return userMapper.selectById(id);
    }

    public IPage<User> getUserList(int currentPage, int pageSize){
        Page<User> page = new Page<>(currentPage, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        return userMapper.selectPage(page, queryWrapper);
    }

    public boolean deleteUser(int id){
        if(userMapper.deleteById(id) > 0){
            return true;
        }
        return false;
    }

}

 

  11.创建Controller

@RestController
@RequestMapping("/user")
@Api(tags="用户接口")    //@Api修饰整个类,描述Controller的作用
public class UserController {

    @Resource
    private UserService userService;


    @ApiOperation(value="value:添加用户", notes="notes:添加用户", tags="添加")   //@ApiOperation描述一个类的一个方法,或者说一个接口
    @PostMapping("/add")
    public String addUser(User user) {
        if(userService.addUser(user)){
            return "Success";
        }
        return "Failure";
    }


    @ApiOperation(value="修改用户", notes="修改用户", tags="修改")
    @PostMapping("/update")
    public String updateUser(User user) {
        if(userService.updateUser(user)){
            return "Success";
        }
        return "Failure";
    }


    @ApiOperation(value="获取用户详情", notes="获取用户详情", tags="查询")
    @ApiImplicitParam(name="id", value="用户ID", dataType="int", required=true, paramType="path")   //@ApiImplicitParam用于方法,描述方法的参数
    @GetMapping("/get/{id}")
    public User getUser(@PathVariable("id") int id) {
        return userService.getUser(id);
    }


    @ApiOperation(value="获取用户列表", notes="获取用户列表", tags="查询")
    @ApiImplicitParams({    //@ApiImplicitParams用于方法,描述方法的参数(多个)
            @ApiImplicitParam(name="currentPage", value="当前页数", dataType="int", required=true, paramType="query"),
            @ApiImplicitParam(name="pageSize" , value="每页条数" , dataType="int", required=true, paramType="query")
    })
    @GetMapping("/list")
    public IPage<User> getUserList(int currentPage, int pageSize){
        return userService.getUserList(currentPage, pageSize);
    }


//    @ApiIgnore  //@ApiIgnore用于类或者方法上,可以不被swagger显示在页面上
    @ApiOperation(value="删除用户", notes="删除用户", tags="删除")
    @GetMapping("/delete/{id}")
    public String deleteUser(@ApiParam(name="id", value="用户ID", required=true) @PathVariable("id") int id){ //@ApiParam单个参数描述
        if(userService.deleteUser(id)){
            return "Success";
        }
        return "Failure";
    }

}

 

  12.访问 http://localhost:8080/(项目名)/swagger-ui.html 测试

 

posted @ 2020-01-02 10:41  晨M风  阅读(1024)  评论(0编辑  收藏  举报