1.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>
<!-- SpringBoot项目的基础库文件-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spring-boot-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<!-- SpringBoot项目的基础库文件-->
<dependencies>
<!-- web项目库-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 测试所需库-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--数据源-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- alibaba JSON工具 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
<!-- spring boot-mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<!-- pagehelper 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.8</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>4.1.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
<!--日志-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.application.yml:
app:
instance:
code: spring-boot-demo
profile: dev
error:
prefix: Error
server:
port: 7002
tomcat:
max-threads: 500
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://127.0.0.1:3306/demo?serverTimezone=Asia/Shanghai&characterEncoding=utf8&characterSetResults=utf8&autoReconnect=true&failOverReadOnly=false
username: root
password: 123456
hikari:
minimum-idle: 2
maximum-pool-size: 5
connection-test-query: select 1
#禁止掉spring boot自动初始化DataSource相关的代码
autoconfigure:
exclude: org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
logging:
config: classpath:logback-config.xml
file: ${app.instance.code}
path: ./log
level:
root: info
com.example: debug
org.springframework.security: warn
注意:
(1.)logging.file,设置文件,可以是绝对路径,也可以是相对路径。
file:
a
p
p
.
i
n
s
t
a
n
c
e
.
c
o
d
e
l
o
g
g
i
n
g
.
p
a
t
h
,
设
置
目
录
,
会
在
该
目
录
下
创
建
.
l
o
g
文
件
,
并
写
入
日
志
内
容
。
p
a
t
h
:
.
/
l
o
g
如
果
只
配
置
l
o
g
g
i
n
g
.
f
i
l
e
,
会
在
项
目
的
当
前
路
径
下
生
成
一
个
x
x
x
.
l
o
g
日
志
文
件
。
如
果
只
配
置
l
o
g
g
i
n
g
.
p
a
t
h
,
在
{app.instance.code} logging.path,设置目录,会在该目录下创建.log文件,并写入日志内容。 path: ./log 如果只配置 logging.file,会在项目的当前路径下生成一个 xxx.log 日志文件。 如果只配置 logging.path,在
app.instance.codelogging.path,设置目录,会在该目录下创建.log文件,并写入日志内容。path:./log如果只配置logging.file,会在项目的当前路径下生成一个xxx.log日志文件。如果只配置logging.path,在{app.instance.code}文件夹生成一个日志文件为 xxx.log。
二者不能同时使用,如若同时使用,则只有logging.file生效。
3.MyBatisConfig:
mybatis配置类,配置数据源、mapper、实体类扫描包、分页插件
package com.example.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;
import javax.sql.DataSource;
import java.util.Properties;
/**
* Created by Administrator on 2019/7/30.
*/
@Configuration
@MapperScan(value = "com.example.mapper")
public class MyBatisConfiguration implements ApplicationContextAware {
@Bean(name = "spring")
@ConfigurationProperties(prefix="spring.datasource")
@Primary
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
}
@Bean(name="sqlSessionFactory")
@Primary
public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
sqlSessionFactoryBean.setTypeAliasesPackage("com.example.entity");
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/*.xml"));
tk.mybatis.mapper.session.Configuration configuration = new tk.mybatis.mapper.session.Configuration();
configuration.setMapUnderscoreToCamelCase(true);
sqlSessionFactoryBean.setConfiguration(configuration);
// 分页插件
Interceptor interceptor = new PageInterceptor();
Properties properties = new Properties();
properties.setProperty("helperDialect", "mariadb");
// properties.setProperty("offsetAsPageNum", "true");
properties.setProperty("rowBoundsWithCount", "true");
properties.setProperty("reasonable", "true");
properties.setProperty("supportMethodsArguments","true");
properties.setProperty("params","pageNum=page;pageSize=limit;");
interceptor.setProperties(properties);
sqlSessionFactoryBean.setPlugins(new Interceptor[] {interceptor});
return sqlSessionFactoryBean.getObject();
}
@Bean(name="sqlSessionTemplate")
@Primary
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
@Bean(name = "transactionManager")
@Primary
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource());
}
}
测试接口:
4.UserController:
package com.example.controller;
import com.example.entity.User;
import com.example.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* Created by Administrator on 2019/7/29.
*/
@RestController
@Slf4j
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/getUser")
public User index(@RequestParam int id){
log.info("测试数据接口");
return userService.Sel(id);
}
}
5.UserService:
package com.example.service;
import com.example.entity.User;
/**
* Created by Administrator on 2019/7/30.
*/
public interface UserService {
User Sel(int id);
}
6.UserServiceImpl:
package com.example.service.Impl;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
/**
* Created by Administrator on 2019/8/6.
*/
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User Sel(int id) {
return userMapper.selectByPrimaryKey(id);
}
}
7.UserMapper:用到的mybatis的通用mapeer方法,不需要自己单独写方法。
package com.example.mapper;
import com.example.entity.User;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;
/**
* Created by Administrator on 2019/7/30.
*/
@Repository
public interface UserMapper extends Mapper<User> {
}
8.User:
@Data :注解在类上;提供类所有属性的 getting 和 setting 方法,此外还提供了equals、canEqual、hashCode、toString 方法
package com.example.entity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* The type User.
*
* @author lxp
* @date 2019 -07-30 16:01:55
*/
@Data
@Table(name = "user")
public class User {
@Id
@Column(name = "id")
private Integer id;
@Column(name = "user_name")
private String userName;
@Column(name = "pass_word")
private String passWord;
@Column(name = "real_name")
private String realName;
}
9.lockback-config.xml基本配置:
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<contextName>logback</contextName>
<property name="log.path" value="E:\\test\\logback.log" />
<!--输出到控制台-->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<!-- <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>-->
<encoder>
<pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<!--输出到文件-->
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>logback.%d{yyyy-MM-dd}.log</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="console" />
<appender-ref ref="file" />
</root>
<!-- logback为java中的包 -->
<logger name="com.example.controller"/>
<!--logback.LogbackDemo:类的全路径 -->
<logger name="com.example.controller.UserController" level="WARN" additivity="false">
<appender-ref ref="console"/>
</logger>
</configuration>
10.整个目录结构如下:
到此,一个基本的spring2.0的项目搭建完成,测试结果如下: