SpringBoot+Mybatis+Druid的集成

使用SpringBoot能够快速的搭建web项目,减小配置文件的编写,如今也愈来愈多的互联网团队采用SpringBoot来搭建微服务。css

下面主要是记录使用SpringBoot+Mybatis+Druid集成流程,若是搭建过Spring MVC 的项目,其实很容就会使用SpringBoot,毕竟SpringBoot是在Spring 4.x系列上发展起来的。html

1、项目结构

SpringBoot的项目结构和之前的Spring MVC的web项目结构是有一些细微差比的。SpringBoot项目中咱们须要在basePackage下加一个项目入口类,SpringBoot项目再也不须要webapp,前端静态资源放在resources目录下的static目录中,Resources目录下须要编写一个application.yml文件,其实做用和spring的application.xml是相似的,重要代码和配置文件内容将在后面整合流程中体现。前端

项目结构图:java

resources下的mapping存放的是mybatis的mapper配置文件mysql

2、整合流程

2.1项目的maven依赖配置

下面是整个一个SpringBoot项目的pom重要片断,SpringBoot的版本能够根据需求升级,pom文件中将SpringBoot默认的日志和内嵌tomcat都排除掉了,这个可根据我的的爱好来决定是否使用默认的logback日志实现以及是否使用tomcat来做为内嵌容器。本例pom配置中是将log4j2做为项目的日志实现方案,容器采用undertow 。从pom文件能够看出比之前直接用spring+spring mvc搭建时少了不少。git

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


     <dependencies>

        <!-- mybatis spring -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency>

        <!-- 引入mybatis 分页 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.0.0-rc</version>
        </dependency>
        <dependency>
            <groupId>com.github.jsqlparser</groupId>
            <artifactId>jsqlparser</artifactId>
            <version>0.9.5</version>
        </dependency>
        <!-- ali druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.27</version>
        </dependency>
        <!-- mysql driver-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.5</version>
        </dependency>


        <!-- spring boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>
        <!--用于controller单元测试-->
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
         <!--log4j2 Asynchronous Loggers requires disruptor-->
        <dependency>
            <groupId>com.lmax</groupId>
            <artifactId>disruptor</artifactId>
            <version>3.3.6</version>
        </dependency>
    </dependencies>

     <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <dependencies>
                    <!--springboot热部署-->
                    <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>springloaded</artifactId>
                        <version>1.2.8.RELEASE</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
        <finalName>SpringBootTest</finalName>
    </build>

在idea中热部署须要启动自动编译-快捷键Ctrl + Alt + S打开设置面板,勾选Build project automatically选项。github

2.2 项目配置文件

application.yml(ps:也可使用application.properties来编写)是SpringBoot上下文启动的主配置文件,须要注意的是在编写yml配置文件的时候,每一个属性配置的冒号后面必定要空一个字符,若是靠在一块儿将会出现配置文件错误,在idea开发工具中,若是你写的配置文件属性名没有高亮,那就须要注意了,配置文件中使用mysql-connector.6.x版本的驱动,这个版本必定要注意驱动名称和之前的版本是不同的,而且链接的url中必须指定时区(serverTimezone)web

配置内容以下:spring

#Spring boot application.yml


spring:
  #profiles : dev
  #数据源配置,使用阿里巴巴的Druid
  datasource:
    name: mydb
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/wechat?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    minIdle: 1
    maxActive: 2
    initialSize: 1
    timeBetweenEvictionRunsMillis: 3000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 'ZTM' FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false

#mybatis的配置
mybatis:
  type-aliases-package: com.sunyu.concurrent
  config-location: classpath:/mybatis-config.xml
  mapper-locations: classpath*:com/sunyu/concurrent/mapping/*.xml

#启动的服务监听端口
server:
  port: 8080

mybatis-config.xml配置文件内容sql

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
		PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
		"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
	    <!--是否开启缓存-->
		<setting name="cacheEnabled" value="true"/>
		<!--是否开启mybatis自动转驼峰-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--use log4j2-->
        <setting name="logImpl" value="LOG4J2"/>
	</settings>
	<!--配置分页插件-->
    <plugins>
    	<plugin interceptor="com.github.pagehelper.PageInterceptor">
    	</plugin>
    </plugins>
</configuration>

log4j2.xml的配置文件,请参考个人前一篇博客,固然若是你不想用log4j2.xml做为日志默认的配置文件,则须要在application.yml文件中配置指定log的配置文件,参考以下:

logging:
  config: classpath:log4j2-spring.xml

2.3 添加静态资源

若是项目只是提供restful的服务,则能够不用作这个操做。在resources目录下新建static目录,在static下你能够建本身的css目录以及图片的存放目录,甚至是html的页面。

注意:不要static不要写其余名称,SpringBoot一开始的理念就是“约定因为配置”,因此没有为何。

重点:本文添加静态路径的目的主要是存放404,500这些错误处理页面,在实际项目中,咱们也必须定制化本身的错误处理页面,本例是在static下新建了一个errors的目录,而后里面存放一些404,500的html。下面会内容将介绍怎么让SpringBoot转发自动义错误页面。

3、项目入口类

项目入口类就是SpringBoot的项目的启动入口,该类通常建议放在basePackage下。类名称能够自定义,只要不和SpringBoot的注解重名,代码以下:

@SpringBootApplication
@MapperScan("com.hunao.boot.dao")
public class SpringBootMainApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootMainApplication.class, args);
    }

    /**
     * 让SpringBoot项目错误时,使用自定义的错误处理页面显示
     * jdk 1.8 lambda
     * @return
     */
    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return (container -> {
                ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/errors/401.html");
                ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/errors/404.html");
                ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR,
                        "/errors/500.html");
                container.addErrorPages(error401Page, error404Page, error500Page);
        });
    }
}

上面@MapperScan很是重要,使用@MapperScan是告诉SpringBoot去扫描包下Mybatis的Mapper接口类,而后完成自动注入和管理,不然我调用Mapper时将找不到相应的实例。固然还可使用另一种方式在咱们本身开发的每个Mybatis mapper接口上加上@Mapper注解,这是SpringBoot也能够自动扫描完成装配,可是这种方式略显麻烦,每一个mapper都加一个注解。

总结:本文主要是介绍整合流程的思路,包括整合当中须要注意的坑以及生产环境下错误页面自动义处理

相关文章
相关标签/搜索