美文网首页
SpringBoot+Swagger+日志

SpringBoot+Swagger+日志

作者: 煗NUAN | 来源:发表于2020-04-12 16:40 被阅读0次

    一.Swagger

    1.Swagger简介

    • swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件.

    • Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单.

    2.Swagger注解

    • @Api:用在请求的类上,表示对类的说明

      • tags="说明该类的作用,可以在UI界面上看到的注解"
      • value="该参数没什么意义,在UI界面上也看到,所以不需要配置"
      @Api(tags="APP用户注册Controller")
      
    • @ApiOperation:用在请求的方法上,说明方法的用途、作用

      • value="说明方法的用途、作用"
      • notes="方法的备注说明"
      @ApiOperation(value="用户注册",notes="手机号、密码都是必输项,年龄随边填,但必须是数字")
      
    • @ApiParam:用于方法,参数,字段说明,表示对参数的添加元数据(说明或是否必填等)

      • name:属性名称
      • value:属性值
      • defaultValue:默认属性值
      • required:是否属性必填
      • example:举例子
      @ApiOperation(value = "传设置过期时间")
      @RequestMapping(value = "/expire", method = RequestMethod.POST)
      public boolean expire(@ApiParam(name = "key", value = "cache key", required = true) @RequestParam("key")String key,@ApiParam(name = "expireSecond", value = "key过期时间:秒", required = true)@RequestParam("expireSecond") Integer expireSecond){
        checkParams(key);
        log.info("key:{},", key);
        return redisService.expire(key, expireSecond);
      }
      
    • @ApiImplicitParams:用在请求的方法上,表示一组参数说明

      • @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
        • name:参数名
        • value:参数的汉字说明、解释
        • required:参数是否必须传
        • paramType:参数放在哪个地方
          • header --> 请求参数的获取:@RequestHeader
          • query --> 请求参数的获取:@RequestParam
          • path(用于restful接口)--> 请求参数的获取:@PathVariable
          • body(不常用)
          • form(不常用)
        • dataType:参数类型,默认String,其它值dataType="Integer"
        • defaultValue:参数的默认值
      @ApiImplicitParams({
        @ApiImplicitParam(name="mobile",value="手机号",required=true,paramType="form"),
        @ApiImplicitParam(name="password",value="密码",required=true,paramType="form"),
        @ApiImplicitParam(name="age",value="年龄", required=true,paramType="form",dataType="Integer")
      })
      
    • @ApiResponses:用在请求的方法上,表示一组响应

      • @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
        • code:数字,例如400
        • message:信息,例如"请求参数没填好"
        • response:抛出异常的类
      @ApiOperation(value = "select1请求",notes = "多个参数,多种的查询参数类型")
      @ApiResponses({
        @ApiResponse(code=400,message="请求参数没填好"),
        @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
      })
      
    • @ApiModel:用于响应类上,表示一个返回响应数据的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候)

      • @ApiModelProperty:用在属性上,描述响应类的属性
      @ApiModel(description= "返回响应数据")
      public class RestMessage implements Serializable{
          @ApiModelProperty(value = "是否成功")
          private boolean success=true;
          @ApiModelProperty(value = "返回对象")
          private Object data;
          @ApiModelProperty(value = "错误编号")
          private Integer errCode;
          @ApiModelProperty(value = "错误信息")
          private String message;
          /* getter/setter */
      }
      

    二.SpringBoot整合Swagger

    1.新建SpringBoot项目

    01.jpg 02.jpg

    2.添加依赖

    <!--SpringBoot整合mybatis-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.2</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.15</version>
            </dependency>
    
            <!-- swagger -->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>2.9.2</version>
            </dependency>
            <!-- swagger-ui -->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>2.9.2</version>
            </dependency>
    
    • 添加依赖后的pom文件
    <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.6.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.ym</groupId>
        <artifactId>spring_boot_swagger</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>war</packaging>
        <name>spring_boot_swagger</name>
        <description>Demo project for Spring Boot</description>
    
        <properties>
            <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-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    
            <!--SpringBoot整合mybatis-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.2</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.15</version>
            </dependency>
    
            <!-- swagger -->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>2.9.2</version>
            </dependency>
            <!-- swagger-ui -->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>2.9.2</version>
            </dependency>
    
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    

    3.resource包下新建application.yml文件

    • 也可以使用application.properties进行配置
    server:
      port: 8080
      # 指定端口
    spring:
      # 配置数据源
      datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        url: jdbc:mysql://localhost:3307/datatest?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
        driver-class-name: com.mysql.cj.jdbc.Driver
        username: root
        password: root
    # 配置mybatis
    mybatis:
      type-aliases-package: com.ym.pojo
      mapper-locations: classpath*:mapper/*Mapper.xml
    # 日志
    logging:
      level:
        root: info  #使用error级别,项目启动不起来,原因还在排查中
      file:
        path: mylog   #日志文件所在的包路径
    # 配置swagger
    swagger:
      basePackage: com.ym
      title: User CRUD SpringBoot Swagger
      version: v1.0
      description: this is a user crud function
      contact: YanM
      url: www.ym.com
    

    4.创建swagger2的配置类

    package com.ym.config;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.Contact;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
    
        @Value ("${swagger.basePackage}")
        private String basePackage; //扫描controller的包名
    
        @Value ("${swagger.title}")
        private String title;  //在线文档的标题
    
        @Value ("${swagger.version}")
        private String version;  //文档的版本
    
        @Value ("${swagger.description}")
        private String description;  //在线文档的描述
    
        @Value ("${swagger.contact}")
        private String contact; //联系人
    
        @Value ("${swagger.url}")
        private String url; //URL
    
        @Bean
        public Docket api(){
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())   //函数返回一个ApiSelectorBuilder实例来控制哪些接口暴露给swagger来展现
                    .select()
                    .apis(RequestHandlerSelectors.basePackage(basePackage))
                    .paths(PathSelectors.any())
                    .build();
        }
    
        private ApiInfo apiInfo(){
            return new ApiInfoBuilder()
                    .title(title)
                    .description(description)
                    .termsOfServiceUrl(url)
                    .version(version)
                    .contact(new Contact(contact,url,url))
                    .build();
        }
    }
    

    5.pojo层

    package com.ym.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
        private int uid;
        private String name;
        private String sex;
        private int age;
        private String address;
    }
    

    6.dao层接口

    • 接口上需要@Mapper注解
    package com.ym.dao;
    
    import com.ym.pojo.User;
    import org.apache.ibatis.annotations.Mapper;
    
    import java.util.List;
    
    @Mapper
    public interface IUserDao {
        List<User> getAllUsers();
    
        User getUserByUid(int uid);
    
        int editUser(User user);
    
        int deleteUserByUid(int uid);
    
        int saveUser(User user);
    }
    

    7.与dao层接口对应的mapper文件

    • 最好在添加一个resultMap
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <!-- 整个映射文件为mapper节点,里面包含namespace属性 -->
    <mapper namespace="com.ym.dao.IUserDao">
    
        <sql id="all">
            select * from users
        </sql>
    
        <select id="getAllUsers" resultType="user">
            <include refid="all" />
        </select>
    
    
        <select id="getUserByUid" resultType="user">
            select * from users where uid=#{uid}
        </select>
    
        <update id="editUser">
            update users
            <set>
                <if test="name != null and name != ''">
                    name = #{name},
                </if>
                <if test="sex != null and sex != ''">
                    sex = #{sex},
                </if>
                <if test="age != 0">
                    age = #{age},
                </if>
                <if test="address != null and address != ''">
                    address = #{address},
                </if>
            </set>
            where uid = #{uid}
        </update>
    
        <delete id="deleteUserByUid">
            delete from users where uid=#{uid}
        </delete>
    
        <insert id="saveUser">
            insert into users values (default ,#{name},#{sex},#{age},#{address})
        </insert>
    </mapper>
    

    8.service层接口

    package com.ym.service;
    
    import com.ym.pojo.User;
    
    import java.util.List;
    
    
    public interface IUserService {
        List<User> getAllUsers();
    
        int editUser(User user);
    
        int deleteUserByUid(int uid);
    
        int saveUser(User user);
    }
    

    9.service层实现类

    package com.ym.service.impl;
    
    import com.ym.dao.IUserDao;
    import com.ym.pojo.User;
    import com.ym.service.IUserService;
    import org.springframework.stereotype.Service;
    
    import javax.annotation.Resource;
    import java.util.List;
    
    
    @Service
    public class UserService implements IUserService {
    
        @Resource
        private IUserDao userDao;
    
        @Override
        public List<User> getAllUsers() {
            return userDao.getAllUsers();
        }
    
        @Override
        public User getUserByUid(int uid) {
            return userDao.getUserByUid(uid);
        }
    
        @Override
        public int editUser(User user) {
            return userDao.editUser(user);
        }
    
        @Override
        public int deleteUserByUid(int uid) {
            return userDao.deleteUserByUid(uid);
        }
    
        @Override
        public int saveUser(User user) {
            return userDao.saveUser(user);
        }
    }
    

    10.controller层

    package com.ym.controller;
    
    import com.ym.pojo.User;
    import com.ym.service.IUserService;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import org.springframework.web.bind.annotation.*;
    
    import javax.annotation.Resource;
    import java.util.List;
    
    
    @RestController
    @Api(tags = "操作用户信息-UserController")
    public class UserController {
    
        @Resource
        private IUserService userService;
    
        @GetMapping("/allUser")
        @ApiOperation(value = "获取所有的用户信息")
        public List<User> queryAllUser(){
            List<User> users = userService.getAllUsers();
            return users;
        }
    
    
        @PostMapping("/editUser")
        @ApiOperation(value = "修改用户信息")
        public void editUser(User user){
            userService.editUser(user);
        }
    
    
        @GetMapping("/deleteUser/{uid}")
        @ApiOperation(value = "删除用户")
        public void deleteUser(@PathVariable int uid){
            userService.deleteUserByUid(uid);
        }
    
        @PostMapping("/saveUser")
        @ApiOperation(value = "保存用户信息")
        public void saveUser(User user){
            userService.saveUser(user);
        }
    }
    

    11.Swagger访问

    • 在地址栏中输入下面地址就可以访问(SpringBoot)

    http://localhost:8080/swagger-ui.html

    swagger访问.jpg
    swagger访问2.jpg

    12.目录结构

    SpringBoot+Swagger目录结构.jpg

    相关文章

      网友评论

          本文标题:SpringBoot+Swagger+日志

          本文链接:https://www.haomeiwen.com/subject/nmhbmhtx.html