说明
该文档为搭建spring+spring mvc+MyBatis工程的快速构建文档
演示环境
系统:macOS 10.12.5
JDK:1.8.121
IDE:Intellij Idea 2017.1.4
项目管理:Gradle 3.5
数据库:mysql 5.7.17
步骤
1.使用idea新建工程:
- 1.点击New -Project,选择Spring Initializr进行初始化,默认配置,点击next
- 2.TYPE选择Gradle Project,其他参数自行决定,点击next
- 3.选择依赖,由于是ssm工程,故选择Core-AOP,Web-Web,以及SQL-MyBatis,和SQL-MySql,如果使用Thymeleaf为页面模板则需选择Template Engines-Thymeleaf,点击next
- 4.出现Gradle选择窗口,可以选择IDE自带gradle,也可选择安装的gradle(本人使用安装的gradle)
- 5.最后IDE将进行工程的创建,并添加依赖
2.修改默认的build.gradle,添加所需依赖
- 1.修改仓库,添加本地和阿里仓库:
将默认的仓库:
repositories {
mavenCentral()
}
修改为
repositories {
mavenLocal()
maven { url = "http://maven.aliyun.com/nexus/content/groups/public" }
mavenCentral()
}
- 2.修改默认plugin,并添加"war"的plugin:
将其中的插件eclipse删除:
apply plugin: 'eclipse'
添加
apply plugin: 'idea'
apply plugin: 'war'
- 3.添加druid,在dependencies添加以下参数:
compile('com.alibaba:druid:1.0.31')
application配置文件修改
- 1.建议将默认application.properties改为application.yml格式(接下去配置,将以.yml格式进行)
- 2.添加数据库配置
spring:
profiles:
active: dev
datasource:
name: girl
url: jdbc:mysql://127.0.0.1:3306/dbgirl
username: root
password: 1234
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
- 3.添加mybatis配置
mybatis:
mapperLocations: classpath:mapper/*.xml # 映射文件所在目录
typeAliasesPackage: com.example.dao # 程序所在目录
代码修改
- 1.需要在生成的默认启动类DemoApplication添加mybatis的扫描,添加以下注解
@MapperScan(basePackages = "com.demo.dao")
- 2.dao下的类需要加上注解@Mapper
mybatis默认xml内容,主要提供文件头,内容自行填充,注意修改mapper的namespace,即映射的class
<?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.demo.dao.DemoDao">
</mapper>
打成war包额外配置
以上默认的工程只能打成jar包,如果需要打成war包,除了需要在build.gradle中添加plugin 'war'之外(之前步骤已经添加),还需加入配置。创建DemoInit.class,并填入以下代码:
public class DemoInit extends SpringBootServletInitializer{
@Override
public SpringApplicationBuilder configure(SpringApplicationBuilder builder){
return builder.sources(DemoApplication.class);
}
其他内容
构建的jar包内置embed tomcat,可直接启动,也可构建成war包放入tomcat启动