1.创建maven项目,jdk8以及以上,修改pom.xml,新增依赖
org.springframework.boot
spring-boot-starter-parent
1.5.2.RELEASE
pom
org.springframework.boot
spring-boot-starter-web
1.5.2.RELEASE
org.springframework
spring-tx
4.3.7.RELEASE
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.2.0
com.alibaba
druid
1.0.25
com.baomidou
mybatis-plus
2.1.0
org.aspectj
aspectjweaver
1.8.4
mysql
mysql-connector-java
5.1.36
org.springframework.boot
spring-boot-starter-freemarker
1.5.9.RELEASE
org.freemarker
freemarker
2.3.22
2.配置DataSource,使用Druid作为连接池
package com.tany.demo.conf;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.alibaba.druid.pool.DruidDataSource;
/**
* DataSource config
*
* @author tanyong
* @version
Id:DruidDataSourceConfig.java,v0.12017年11月14日上午11:50:25tanyongExp
I
d
:
D
r
u
i
d
D
a
t
a
S
o
u
r
c
e
C
o
n
f
i
g
.
j
a
v
a
,
v
0.1
2017
年
11
月
14
日
上
午
11
:
50
:
25
t
a
n
y
o
n
g
E
x
p
*/
@Configuration
@Primary
//在同样的DataSource中,首先使用被标注的DataSource
public class DruidDataSourceConfig extends DataSourceProperties {
private static final Logger logger = LoggerFactory.getLogger(DruidDataSourceConfig.class);
/**
* 数据库链接地址
*/
@Value("${jdbc.url}")
private String dbUrl;
/**
* jdbc user
*/
@Value("${jdbc.user}")
private String username;
/**
* jdbc jdbc.pwd
*/
@Value("${jdbc.pwd}")
private String password;
/**
* 驱动
*/
@Value("${jdbc.driver}")
private String driverClassName;
/**
* 连接池初始化大小
*/
@Value("${jdbc.initialSize}")
private int initialSize;
/**
* 最小连接池数量
*/
@Value("${jdbc.minIdle}")
private int minIdle;
/**
* 连接池最大活动连接数
*/
@Value("${jdbc.maxActive}")
private int maxActive;
/**
* 获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降,
* 如果需要可以通过配置useUnfairLock属性为true使用非公平锁。
*/
@Value("${jdbc.maxWait}")
private int maxWait;
/**
* 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
*/
@Value("${jdbc.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
/**
* 配置一个连接在池中最小生存的时间,单位是毫秒
*/
@Value("${jdbc.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
/**
* 用来检测连接是否有效的sql,要求是一个查询语句。如果validationQuery为null,
* testOnBorrow、testOnReturn、testWhileIdle都不会其作用
*/
@Value("${jdbc.validationQuery}")
private String validationQuery;
/**
* 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,
* 执行validationQuery检测连接是否有效
*/
@Value("${jdbc.testWhileIdle}")
private boolean testWhileIdle;
/**
* 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
*/
@Value("${jdbc.testOnBorrow}")
private boolean testOnBorrow;
/**
* 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
*/
@Value("${jdbc.testOnReturn}")
private boolean testOnReturn;
/**
* 是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。
*/
@Value("${jdbc.poolPreparedStatements}")
private boolean poolPreparedStatements;
/**
* 每个连接上PSCache的大小
*/
@Value("${jdbc.maxPoolPreparedStatementPerConnectionSize}")
private int maxPoolPreparedStatementPerConnectionSize;
/**
* 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
*/
@Value("${jdbc.filters}")
private String filters;
/**
* 通过connectProperties属性来打开mergeSql功能;慢SQL记录
*/
@Value("{jdbc.connectionProperties}")
private String connectionProperties;
/**
* 合并多个DruidDataSource的监控数据
*/
@Value("{jdbc.useGlobalDataSourceStat}")
private String useGlobalDataSourceStat;
@Bean
public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(this.dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
//configuration
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource
.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
logger.error("druid configuration initialization filter error:[{}]", e);
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
}
3.配置Druid监控
package com.tany.demo.conf;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
@Configuration
public class DruidMonitorConfig {
/**
* 注册ServletRegistrationBean
* @return
*/
@Bean
public ServletRegistrationBean registrationBean() {
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),
"/api/druid/*");
/** 初始化参数配置,initParams**/
//白名单
// bean.addInitParameter("allow", "127.0.0.1");//多个ip逗号隔开
//IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
//bean.addInitParameter("deny", "192.168.1.73");
//登录查看信息的账号密码.
bean.addInitParameter("loginUsername", "admin");
bean.addInitParameter("loginPassword", "qaz123456");
//是否能够重置数据.
bean.addInitParameter("resetEnable", "false");
return bean;
}
/**
* 注册FilterRegistrationBean
* @return
*/
@Bean
public FilterRegistrationBean druidStatFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean(new WebStatFilter());
//添加过滤规则.
bean.addUrlPatterns("/*");
//添加不需要忽略的格式信息.
bean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/api/druid/*");
return bean;
}
}
4.mybaits plus 配置
package com.tany.demo.conf;
import javax.sql.DataSource;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
//import com.baomidou.mybatisplus.MybatisConfiguration;
//import com.baomidou.mybatisplus.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.enums.DBType;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
/**
* mybaits 配置
*
* @author tanyong
* @version
Id:MybatisPlusConfig.java,v0.12017年11月15日下午3:19:49tanyongExp
I
d
:
M
y
b
a
t
i
s
P
l
u
s
C
o
n
f
i
g
.
j
a
v
a
,
v
0.1
2017
年
11
月
15
日
下
午
3
:
19
:
49
t
a
n
y
o
n
g
E
x
p
*/
@Configuration
@EnableConfigurationProperties(MybatisProperties.class)
public class MybatisPlusConfig implements TransactionManagementConfigurer {
@Autowired
private DataSource dataSource;
@Autowired
private MybatisProperties properties;
@Autowired
private ResourceLoader resourceLoader = new DefaultResourceLoader();
@Autowired(required = false)
private Interceptor[] interceptors;
@Autowired(required = false)
private DatabaseIdProvider databaseIdProvider;
/**
* mybatis-plus分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor page = new PaginationInterceptor();
page.setDialectType("mysql");
return page;
}
/**
* 声明默认 transactionManager
*
* @return
*/
public PlatformTransactionManager transactionManager() {
DataSourceTransactionManager sourceTransactionManager = new DataSourceTransactionManager();
sourceTransactionManager.setDataSource(dataSource);
return sourceTransactionManager;
}
/**
* 默认transactionManager
* @see org.springframework.transaction.annotation.TransactionManagementConfigurer#annotationDrivenTransactionManager()
*/
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return transactionManager();
}
/**
* 这里全部使用mybatis-autoconfigure 已经自动加载的资源。不手动指定
* 配置文件和mybatis-boot的配置文件同步
* @return
*/
@Bean
public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() {
MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
mybatisPlus.setDataSource(dataSource);
mybatisPlus.setVfs(SpringBootVFS.class);
if (StringUtils.hasText(this.properties.getConfigLocation())) {
mybatisPlus.setConfigLocation(
this.resourceLoader.getResource(this.properties.getConfigLocation()));
}
mybatisPlus.setConfiguration(properties.getConfiguration());
if (!ObjectUtils.isEmpty(this.interceptors)) {
mybatisPlus.setPlugins(this.interceptors);
}
// MP 全局配置,更多内容进入类看注释
GlobalConfiguration globalConfig = new GlobalConfiguration();
globalConfig.setDbType(DBType.MYSQL.name());//数据库类型
// ID 策略 AUTO->`0`("数据库ID自增") INPUT->`1`(用户输入ID") ID_WORKER->`2`("全局唯一ID") UUID->`3`("全局唯一ID")
globalConfig.setIdType(0);
//MP 属性下划线 转 驼峰 , 如果原生配置 mc.setMapUnderscoreToCamelCase(true) 开启,该配置可以无。
//globalConfig.setDbColumnUnderline(true);
mybatisPlus.setGlobalConfig(globalConfig);
// MybatisConfiguration mc = new MybatisConfiguration();
// // 对于完全自定义的mapper需要加此项配置,才能实现下划线转驼峰
// //mc.setMapUnderscoreToCamelCase(true);
// mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
// mybatisPlus.setConfiguration(mc);
if (this.databaseIdProvider != null) {
mybatisPlus.setDatabaseIdProvider(this.databaseIdProvider);
}
if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
mybatisPlus.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
}
if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
mybatisPlus.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
}
if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
mybatisPlus.setMapperLocations(this.properties.resolveMapperLocations());
}
return mybatisPlus;
}
}
5.FreeMarkerConfig 配置
package com.tany.demo.conf;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.freemarker.FreeMarkerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
/**
*
* FreeMarkerConfig
* @author tanyong
* @version
Id:FreeMarkerConfig.java,v0.12018年2月27日下午5:25:46ThinkPadExp
I
d
:
F
r
e
e
M
a
r
k
e
r
C
o
n
f
i
g
.
j
a
v
a
,
v
0.1
2018
年
2
月
27
日
下
午
5
:
25
:
46
T
h
i
n
k
P
a
d
E
x
p
*/
@Configuration
public class FreeMarkerConfig {
@Bean
@ConditionalOnMissingBean(FreeMarkerConfig.class)
public FreeMarkerConfigurer freeMarkerConfigurer() {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
configurer.setConfigLocation(resolver.getResource("classpath:/freemarker.properties"));
configurer.setTemplateLoaderPath(FreeMarkerProperties.DEFAULT_TEMPLATE_LOADER_PATH);
configurer.setPreferFileSystemAccess(true);
configurer.setDefaultEncoding("UTF-8");
return configurer;
}
@Bean
@ConditionalOnMissingBean(name = "freeMarkerViewResolver")
@ConditionalOnProperty(name = "spring.freemarker.enabled", matchIfMissing = true)
public FreeMarkerViewResolver freeMarkerViewResolver() {
FreeMarkerViewResolver viewResolver = new FreeMarkerViewResolver();
viewResolver.setCache(true);
viewResolver.setContentType("text/html;charset=UTF-8");
//resolver.setViewNames(getViewNames());
viewResolver.setExposeRequestAttributes(true);
viewResolver.setAllowRequestOverride(true);
viewResolver.setAllowSessionOverride(true);
viewResolver.setExposeSessionAttributes(true);
viewResolver.setExposeSpringMacroHelpers(true);
viewResolver.setRequestContextAttribute("request");
viewResolver.setOrder(Ordered.LOWEST_PRECEDENCE - 5);
viewResolver.setSuffix(".ftl");
viewResolver.setPrefix("/");
return viewResolver;
}
}
6.在src/main/resources 新建application.properties
测试环境
spring.profiles.active=test
生产环境
spring.profiles.active=prod
根据不同的环境,新建不同的配置文件,测试环境配置文件application-test.properties
mysql
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/test
jdbc.user=user
jdbc.pwd=passwd
jdbc.initialSize=5
jdbc.minIdle=5
jdbc.maxActive=20
jdbc.maxWait=600000
jdbc.timeBetweenEvictionRunsMillis=600000
jdbc.minEvictableIdleTimeMillis=300000
jdbc.validationQuery=SELECT 1 FROM DUAL
jdbc.testWhileIdle=true
jdbc.testOnBorrow=false
jdbc.testOnReturn=false
jdbc.poolPreparedStatements=false
jdbc.maxPoolPreparedStatementPerConnectionSize=20
jdbc.filters=stat,wall,log4j
jdbc.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
jdbc.useGlobalDataSourceStat=true
debug=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.force=true
spring.mvc.favicon.enabled=false
mybatis
mybatis.configLocation=classpath:mybatis-config.xml
mybatis.mapper-locations=classpath:com/tany/demo/mapper/xml/*Mapper.xml
mybatis.typeAliasesPackage=com.tany.demo.entity
新建freemarker.properties
locale=CHINA
default_encoding=UTF-8
output_encoding=UTF-8
number_format=#.##
date_format=yyyy-MM-dd
time_format=HH:mm:Ss
datetime_format=yyyy-MM-dd HH:mm:Ss
template_update_delay=0
auto_import=”/global_library.ftl” as model
新建logback.xml