网上看到很多spring boot入门文章,但大多不全面,一般只记录简单的创建流程,鉴于此,记录下搭建基于gradle的spring boot项目的一个详细步骤及配置,包括mybatis和日志配置、调试、发布等。本人刚开始尝试记录一些自己的学习过程,文笔和表达能力有限,望大家包含和支持!
系统及项目要求
1.jdk1.8
2.项目构建工具:gradle
3.开发工具:idea
4.spring boot2.0
项目创建过程
-
根据图示创建项目
- 一直点击next, 直到点击 finish
-
gradle设置
-
目录结构
修改配置
-
修改目录结构(controller/service等包自行添加)
修改gradle配置文件,引入新的依赖
buildscript {
ext {
springBootVersion = '2.0.0.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.springboot'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
// 移除spring boot自带的日志管理工具,否则会有冲突
configurations {
compile.exclude module: 'spring-boot-starter-logging'
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-jdbc')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2')
compile('org.springframework.boot:spring-boot-starter-log4j2')
compile("com.alibaba:druid:1.1.0")
runtime('mysql:mysql-connector-java')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
- 修改启动文件 BootstudyApplication.java
package com.springboot.bootstudy;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
// TODO 自动扫描的包,请根据实际的包结构修改
@SpringBootApplication(scanBasePackages = {
"com.springboot.bootstudy"
})
// TODO mybatis扫描的mapper接口文件,请根据实际的包结构修改
@MapperScan(basePackages = {
"com.springboot.bootstudy.mybatis.mapper"
})
// 扫描servlet注解(如果代码中含有servlet相关注解,需要加上此的注解)
@ServletComponentScan
public class BootstudyApplication {
public static void main(String[] args) {
SpringApplication.run(BootstudyApplication.class, args);
}
}
- 修改yml配置文件(application-daily.yml)
# 设置端口
server:
port: 8080
spring:
# 设置数据源,注意命名
datasource:
name:
url: jdbc:mysql://10.0.10.41:3306/shinemo_open?autoReconnect=true&failOverReadOnly=false&maxReconnects=10&characterEncoding=UTF8
username: root
password: shinemo123
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
filters: stat
connectionProperties: druid.stat.slowSqlMillis=50
max-active: 5
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
# 设置环境
profiles:
active: daily
# mybatis 配置xml文件路径和实体包路径
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.springboot.bootstudy.mybatis.domain.model
# 设置日志文件路径
logging:
config: classpath:log4j2-daily.xml
application-online.yml参考上面修改
- log4j.xml 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="info">
<Properties>
<Property name="app.log.dir">/tmp/logs/bootstudy</Property>
<Property name="root.log.level">warn</Property>
</Properties>
<!-- ===================================================================== -->
<!-- appender 配置 -->
<!-- ===================================================================== -->
<Appenders>
<RollingRandomAccessFile name="error.appender"
append="true"
immediateFlush="true"
fileName="${app.log.dir}/app-error.log"
filePattern="${app.log.dir}/%d{yyyy/MM}/app-error-%d{dd}-%i.log">
<PatternLayout charset="UTF-8">
<Pattern>%d{HH:mm:ss,SSS} %-5level [%t] %c{1.}.%M(%L) - %m%n</Pattern>
</PatternLayout>
<Policies>
<!-- 这里的1的单位是filePattern里面的%d{yyyy-MM-dd}-%i.log 最小的单位dd表示分钟 -->
<TimeBasedTriggeringPolicy interval="1" modulate="false"/>
</Policies>
<!-- 最多保留文件数 -->
<DefaultRolloverStrategy max="10"/>
</RollingRandomAccessFile>
<RollingRandomAccessFile name="access.appender"
append="true"
immediateFlush="true"
fileName="${app.log.dir}/access.log"
filePattern="${app.log.dir}/%d{yyyy/MM}/access-%d{dd}-%i.log">
<PatternLayout charset="UTF-8">
<Pattern>%d{HH:mm:ss} - %m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="false"/>
</Policies>
<DefaultRolloverStrategy max="31"/>
</RollingRandomAccessFile>
</Appenders>
<!-- ===================================================================== -->
<!-- logger 配置 -->
<!-- ===================================================================== -->
<Loggers>
<Root level="${root.log.level}">
<AppenderRef ref="error.appender"/>
</Root>
<Logger name="error.log" level="WARN" additivity="false">
<AppenderRef ref="error.appender"/>
</Logger>
<Logger name="access.log" level="INFO" additivity="false">
<AppenderRef ref="access.appender"/>
</Logger>
</Loggers>
</Configuration>
- 打印访问日志的filter
package com.springboot.bootstudy.filter;
/**
* Created by yuanjian on 3/19/18
*
* @author liuyj@shinemo.com
*/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* 打印日志的filter
* Created by yuanjian on 3/15/18
*
* @author liuyj@shinemo.com
*/
@Component
public class LogFilter extends OncePerRequestFilter {
private Logger logger = LoggerFactory.getLogger("access.log");
@Override
public void destroy() {
}
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
int length = request.getContentLength();
ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request, length);
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
try {
chain.doFilter(request, responseWrapper);
} finally {
log(requestWrapper, responseWrapper);
// 将返回值复制到response中,此段代码必须
responseWrapper.copyBodyToResponse();
}
}
/**
* 打印访问日志,可以根据需求定制化
*
* @param requestWrapper 保存了body参数的request
* @param responseWrapper 保存了返回值的response
*/
private void log(ContentCachingRequestWrapper requestWrapper, ContentCachingResponseWrapper responseWrapper) {
// 打印日志
String body = "";
if (requestWrapper.getContentLength() > 0) {
body = new String(requestWrapper.getContentAsByteArray(), StandardCharsets.UTF_8);
}
byte[] resultByte = responseWrapper.getContentAsByteArray();
String result = "";
if (resultByte != null && resultByte.length > 0) {
result = new String(resultByte, StandardCharsets.UTF_8);
}
logger.info("body:{}, result:{}", body, result);
}
}
接下来我们就可以开发spring boot的应用程序了。