您的位置:首页 > 编程语言 > Java开发

快速搭建springBoot+mybatis+pagehelper+druid+lombok+多环境配置

2018-11-05 11:45 686 查看

主要技术框架:springBoot+mybatis+pagehelper+druid+lombok+多环境配置

1.新建一个springBoot项目、勾选需要的jar包

2.pom里引入druid依赖

[code]        <!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.3</version>
</dependency>
<!-- Druid 数据连接池依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.20</version>
</dependency>
<!-- 添加mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>

3.把application.properties改成application.yml

[code]#配置spring视图解析器
spring:
mvc:
view:
prefix: /WEB-INF/views/
suffix: .jsp
devtools:
restart:
enabled: true
session:
store-type: none
#设置端口
server:
port: 80

#pagehelper
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
returnPageInfo: check

 

4.在src/main/ 目录下创建conf 目录,用来存放多环境的配置文件:

5.pom中定义多环境配置,使用maven打包编译时会自动编译当前环境配置文件:

[code]1.定义env标签:
<properties>
<!-- 当前环境标识 -->
<env>dev</env>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

2.配置文件读取

<!-- 多环境配置文件读取 -->
<resources>
<resource>
<directory>src/main/conf/${env}</directory>
<includes>
<include>**</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>

jdbc.properties

[code]#############alibaba druid 连接池配置################
#jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://ip:port/test?useUnicode=true&characterEncoding=UTF-8&rewriteBatchedStatements=true
jdbc.username=root
jdbc.password=
# 配置初始化大小、最小、最大
jdbc.initialSize=10
jdbc.minIdle=10
jdbc.maxActive=40
# 配置获取连接等待超时的时间
jdbc.maxWait=600000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
jdbc.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
jdbc.minEvictableIdleTimeMillis=300000

jdbc.validationQuery=SELECT 'x'
jdbc.testWhileIdle=true
jdbc.testOnBorrow=false
jdbc.testOnReturn=false

# 打开PSCache,并且指定每个连接上PSCache的大小,mysql设置为false
jdbc.poolPreparedStatements=false
jdbc.maxPoolPreparedStatementPerConnectionSize=33

#对于长时间不使用的连接强制关闭
jdbc.removeAbandoned=true
#关闭超过30分钟的空闲连接,1800秒,也就是30分钟
jdbc.removeAbandonedTimeout=1800
#关闭abanded连接时输出错误日志
jdbc.logAbandoned=true
#监控数据库
jdbc.filters=stat

jedis.properties

[code]#########redis配置##########
# Redis服务器地址
redis-pool.host=127.0.0.1
# Redis服务器连接端口
redis-pool.port=6379
# Redis服务器连接密码(默认为空)
redis-pool.password=
# 连接超时时间(毫秒)
redis-pool.timeOut=5000
# 连接池中的最大空闲连接
redis-pool.maxIdle=8
redis-pool.minIdle=1
# 连接池最大阻塞等待时间(使用负值表示没有限制)
redis-pool.maxWaitMillis=5000
# 连接池最大实例
redis-pool.maxTotal=150
#在borrow一个jedis的时候验证其是否可用,可用则返回,不可用则废弃重新创建一个
redis-pool.testOnBorrow=true

读取jdbc.properties属性:

[code]package com.dg.wechat.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
* @CreatUser : lsy
* @CreatTime : 2018/11/2 11:09
*/
@Component
@PropertySource("classpath:jdbc.properties")
@ConfigurationProperties(prefix = "jdbc")
@Data
public class JdbcProperties {

//数据库URL
private String url;
//数据库用户名
private String username;
//数据库密码
private String password;
//初始化链接大小
private int initialSize;
//连接池最大使用链接数量
private int maxActive;
//连接池最大空闲
private int maxIdle;
//连接池最小空闲
private int minIdle;
//连接池最大等待时间
private long maxWait;
//验证数据库是否连通
private String validationQuery;
//配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
private int timeBetweenEvictionRunsMillis;

private int minEvictableIdleTimeMillis;

private boolean testWhileIdle;

private boolean testOnBorrow;

private boolean testOnReturn;

private boolean poolPreparedStatements;

private int maxPoolPreparedStatementPerConnectionSize;

private boolean removeAbandoned;

private int removeAbandonedTimeout;

private boolean logAbandoned;

private String filters;

}

 

6.配置文件读取已经完成,开始配置mybatis属性:

首先初始化mybatis分页插件pagehelper

[code]
/**
* @CreatUser : lsy
* @CreatTime : 2018/11/2 11:12
*/
@Configuration
public class PageHelperConfig {

@Value("${pagehelper.helperDialect}")
private String helperDialect;

@Bean(name = "pageInterceptor")
@Primary//控制实例优先被注入
public PageInterceptor pageInterceptor(){
System.out.println("初始化mybatis分页插件");
PageInterceptor pageInterceptor = new PageInterceptor();
Properties properties = new Properties();
properties.setProperty("helperDialect", helperDialect);
pageInterceptor.setProperties(properties);
return pageInterceptor;
}
}

7.然后初始化Mybatis

/**
* @CreatUser : lsy
* @CreatTime : 2018/11/2 11:42
*/
@Configuration
@EnableTransactionManagement
@MapperScan(value = "com.dg.wechat.dao")
public class MybatisConfig {

/**
* 注入mybatis分页插件
*/
@Resource(name = "pageInterceptor")
private PageInterceptor pageInterceptor;

/**
* 实体类扫描路径
*/
private static final String MODEL_LOCATION = "com.dg.wechat.model.*";
/**
* ,mapper层扫描路径
*/
private static final String MAPPER_LOCATION = "classpath*:/mapper/*.xml";
/**
* mybatis配置文件路径
*/
private static final String CONFIG_LOCATION = "classpath:/mybatis-config.xml";

/**
* 配置alibaba数据源
* @param jdbcProperties
* @return
* @throws SQLException
*/
@Bean
@Primary
public DataSource druidDataSource(JdbcProperties jdbcProperties) throws SQLException {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(jdbcProperties.getUrl());
dataSource.setUsername(jdbcProperties.getUsername());
dataSource.setPassword(jdbcProperties.getPassword());
dataSource.setInitialSize(jdbcProperties.getInitialSize());
dataSource.setMaxActive(jdbcProperties.getMaxActive());
dataSource.setMaxIdle(jdbcProperties.getMaxIdle());
dataSource.setMinIdle(jdbcProperties.getMinIdle());
dataSource.setMaxWait(jdbcProperties.getMaxWait());
dataSource.setValidationQuery(jdbcProperties.getValidationQuery());
dataSource.setTimeBetweenConnectErrorMillis(jdbcProperties.getTimeBetweenEvictionRunsMillis());
dataSource.setMinEvictableIdleTimeMillis(jdbcProperties.getMinEvictableIdleTimeMillis());
dataSource.setTestWhileIdle(jdbcProperties.isTestWhileIdle());
dataSource.setTestOnBorrow(jdbcProperties.isTestOnBorrow());
dataSource.setTestOnReturn(jdbcProperties.isTestOnReturn());
dataSource.setPoolPreparedStatements(jdbcProperties.isPoolPreparedStatements());
dataSource.setMaxPoolPreparedStatementPerConnectionSize(jdbcProperties.getMaxPoolPreparedStatementPerConnectionSize());
dataSource.setRemoveAbandoned(jdbcProperties.isRemoveAbandoned());
dataSource.setRemoveAbandonedTimeout(jdbcProperties.getRemoveAbandonedTimeout());
dataSource.setLogAbandoned(jdbcProperties.isLogAbandoned());
dataSource.setFilters(jdbcProperties.getFilters());
return dataSource;
}

/**
* 注册数据源事务管理
*
* @param dataSource
* @return
*/
@Bean(name = "platformTransactionManager")
public PlatformTransactionManager myBatisTransactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}

/**
* 声明式事务
*
* @param platformTransactionManager
* @return
*/
@Bean(name = "txAdvice")
public TransactionInterceptor transactionInterceptor(PlatformTransactionManager platformTransactionManager) {
TransactionInterceptor transactionInterceptor = new TransactionInterceptor();
transactionInterceptor.setTransactionManager(platformTransactionManager);
Properties transactionAttributes = new Properties();
transactionAttributes.setProperty("create*", "PROPAGATION_REQUIRED,-Throwable");
transactionAttributes.setProperty("insert*", "PROPAGATION_REQUIRED,-Throwable");
transactionAttributes.setProperty("save*", "PROPAGATION_REQUIRED,-Throwable");
transactionAttributes.setProperty("update*", "PROPAGATION_REQUIRED,-Throwable");
transactionAttributes.setProperty("delete*", "PROPAGATION_REQUIRED,-Throwable");
transactionAttributes.setProperty("select*", "PROPAGATION_REQUIRED,-Throwable,readOnly");
transactionInterceptor.setTransactionAttributes(transactionAttributes);
return transactionInterceptor;
}

@Bean
public BeanNameAutoProxyCreator transactionAutoProxy() {
BeanNameAutoProxyCreator transactionAutoProxy = new BeanNameAutoProxyCreator();
transactionAutoProxy.setProxyTargetClass(true);
transactionAutoProxy.setBeanNames("*Service");
transactionAutoProxy.setInterceptorNames("txAdvice");
return transactionAutoProxy;
}

/**
* 配置SqlSessionFactory工厂
*
* @param myBatisDataSource
* @return
* @throws Exception
*/
@Bean
public SqlSessionFactory myBatisSqlSessionFactory(DataSource myBatisDataSource) throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(myBatisDataSource);
sessionFactory.setTypeAliasesPackage(MODEL_LOCATION);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(CONFIG_LOCATION));
//配置mybatis分页插件 果不将PageInterceptor设置到SqlSessionFactoryBean中,导致分页失效
//sessionFactory.setPlugins(new Interceptor[]{pageInterceptor});
return sessionFactory.getObject();
}

}

OK,整合完成!

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: