欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot集成 spring + spring MVC + mybatis + swagger + maven

程序员文章站 2022-07-02 20:57:17
...

spring boot集成 spring + spring MVC + mybatis + swagger + maven

第一步:选择Spring Initializr搭建spring boot
spring boot集成 spring + spring MVC + mybatis + swagger + maven
第二步:配置项目信息
spring boot集成 spring + spring MVC + mybatis + swagger + maven
第三步:选择项目需要的jar包
web必选的
spring boot集成 spring + spring MVC + mybatis + swagger + maven
我用的Mysql数据库选择MySQL,Mybatis
spring boot集成 spring + spring MVC + mybatis + swagger + maven
第四步:配置项目名和项目地址

spring boot集成 spring + spring MVC + mybatis + swagger + maven
第五步:spring boot完整项目结构
spring boot集成 spring + spring MVC + mybatis + swagger + maven

项目实例结构

spring boot集成 spring + spring MVC + mybatis + swagger + maven

第一步:创建User实体类

package com.lbl.springbootdemo.domain;

/**
 * @Author: libl
 * @Date: 2018/9/4 16:37
 * @Description: User实体类
 */
public class User {

    private int id;
    private String name;
    private int age;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

第二步:创建UserDao接口


package com.lbl.springbootdemo.dao;

import com.lbl.springbootdemo.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

/**
 * @Author: libl
 * @Date: 2018/9/4 16:49
 * @Description:
 */
@Mapper
@Repository
public interface UserDao {

    public User findUserById(int id);
}

第三步:创建UserMapper.xml

<?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="com.lbl.springbootdemo.dao.UserDao">

    <select id="findUserById" resultType="com.lbl.springbootdemo.domain.User">
        SELECT * FROM user WHERE id = #{id}
    </select>

</mapper>

第四步:创建UserService接口

package com.lbl.springbootdemo.service;

import com.lbl.springbootdemo.domain.User;

/**
 * @Author: libl
 * @Date: 2018/9/4 16:49
 * @Description:
 */
public interface UserService {
    public User findUserById(int id);
}

第五步:创建UserService类实现UserService接口

package com.lbl.springbootdemo.service.impl;

import com.lbl.springbootdemo.dao.UserDao;
import com.lbl.springbootdemo.domain.User;
import com.lbl.springbootdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: libl
 * @Date: 2018/9/4 16:50
 * @Description:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    @Override
    public User findUserById(int id) {
        return userDao.findUserById(id);
    }
}

第六步:创建Swagger2类
需要先在pom.xml加入2个Swagger依赖

    <!--swagger-start-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>
        <!--swagger-end-->
package com.lbl.springbootdemo.config;

import io.swagger.annotations.ApiOperation;
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;

/**
 * @Author: libl
 * @Date: 2018/9/4 16:51
 * @Description: Restful API 访问路径:http://IP:port/{context-path}/swagger-ui.html
 */

@Configuration //用@Configuration注解该类,等价于XML中配置beans;用@Bean标注方法等价于XML中配置bean。
@EnableSwagger2  //@EnableSwagger2注解来启用Swagger2。
public class Swagger2 {

    /**
     * swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
     *
     * @return
     */
    @Bean
    protected Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) //相当于apis(RequestHandlerSelectors.basePackage("com.lbl.springbootdemo.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 构建 api文档的详细信息函数,这些函数不是必须的,但我都列了出来。
     *
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //页面标题
                .title("title页面标题:用户管理客户端")
                //描述
                .description("description描述:用户的增删改查")
                //版本号
                .version("version版本号:1.0")
                // 许可人url
                .termsOfServiceUrl("termsOfServiceUrl许可人url:https://blog.csdn.net/weixin_39819880")
                //创建人姓名,url,email
                .contact(new Contact("创建人姓名:libl", "url:https://blog.csdn.net/weixin_39819880", "email:aaa@qq.com"))
                // 许可人,许可证
                .license("license许可人,许可证:libl")
                // 许可url
                .licenseUrl("licenseUrl许可url:https://blog.csdn.net/weixin_39819880")
                .build();
    }

}

第七步:创建UserController类

package com.lbl.springbootdemo.controller;

import com.lbl.springbootdemo.domain.User;
import com.lbl.springbootdemo.service.impl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: libl
 * @Date: 2018/9/4 16:50
 * @Description:
 */
@RestController//相当于@Controller与@ResponseBody
@Api(value = "user", description = "用户管理", tags = "用户管理")
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserServiceImpl userService;

    @ApiOperation(value = "查询用户信息")
    @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Integer", paramType = "query")
    @RequestMapping(value = "/find", method = RequestMethod.POST)
    public User findUserById(int id) {
        User user = userService.findUserById(id);
        return user;
    }
}

第七步:配置application.properties

#项目的根路径
server.servlet.context-path=/springboot-demo
#设置UTF-8编码
spring.http.encoding.enabled=true
spring.http.encoding.charset=UTF-8
server.tomcat.uri-encoding=UTF-8
#tomcat端口
server.port=8022
#数据连接
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
#Mybatis扫描
mybatis.mapper-locations=classpath*:mapper/*.xml

pom.xml文件

<?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>com.lbl</groupId>
    <artifactId>springboot-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot-demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.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.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--swagger-start-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>
        <!--swagger-end-->
    </dependencies>

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

</project>

数据库
spring boot集成 spring + spring MVC + mybatis + swagger + maven
访问路径:http://IP:port/{context-path}/swagger-ui.html
访问http://127.0.0.1:8022/springboot-demo/swagger-ui.html

spring boot集成 spring + spring MVC + mybatis + swagger + maven
先点击 Show/Hide 再点击 Expand Operations

spring boot集成 spring + spring MVC + mybatis + swagger + maven
输入参数id 点击Try it out!

spring boot集成 spring + spring MVC + mybatis + swagger + maven

Swagger笔记

-----------------------------------------------------------------------------------------------------------------------------------
Swagger注解说明:
@Api:用在类上,说明该类的作用
@ApiOperation:用在方法上,说明方法的作用
@ApiImplicitParams:用在方法上包含一组参数说明
@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
paramType:参数放在哪个地方
header-->请求参数的获取:@RequestHeader
query-->请求参数的获取:@RequestParam
path(用于restful接口)-->请求参数的获取:@PathVariable
body(不常用)
form(不常用)
name:参数名
dataType:参数类型
required:参数是否必须传
value:参数的意思
defaultValue:参数的默认值
@ApiResponses:用于表示一组响应
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出异常的类
@ApiModel:描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候)
@ApiModelProperty:描述一个model的属性
-----------------------------------------------------------------------------------------------------------------------------------