SpringBoot+Swagger+日志

2020-04-12  本文已影响0人  煗NUAN

一.Swagger

1.Swagger简介

2.Swagger注解

二.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>
<?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文件

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层接口

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文件

<?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访问

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

swagger访问.jpg
swagger访问2.jpg

12.目录结构

SpringBoot+Swagger目录结构.jpg
上一篇下一篇

猜你喜欢

热点阅读