快速搭建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,整合完成!
阅读更多相关文章推荐
- maven+spring boot+druid+mysql+mybatis+pagehelper+jsp环境搭建
- Spring Boot : 集成mybatis、pagehelper插件、开启事务、druid数据源配置、mybatis-generator(十一)
- SpringBoot 使用yml配置 mybatis+pagehelper+druid+freemarker实例
- Shiro 学习(一)基于SpringBoot的Apache Shiro环境快速搭建与配置
- SpringBoot+Mybatis+ Druid+PageHelper 实现多数据源并分页
- Springboot+Mybatis+Pagehelper+Aop动态配置Oracle、Mysql数据源
- SpringBoot+Mybatis+ Druid+PageHelper 实现多数据源并分页
- Spring Boot+Mybatis+Druid+PageHelper实现多数据源并分页的方法
- SpringBoot+Mybatis+ Druid+PageHelper 实现多数据源并分页
- spring boot / cloud (十七) 快速搭建注册中心和配置中心
- Spring Boot整合Mybatis-Plus和PageHelper分页插件,附项目源码
- Mybatis在非spring环境下配置文件中使用外部数据源(druidDatasource)
- Springboot + Mybatis + druid 配置
- SpringBoot集成MyBatis、PageHelper和通用Mapper
- SpringBoot + MyBatis + MySQL + Maven在Intellij IDEA下开发环境的搭建
- 【SpringBoot】快速搭建SpringBoot+Maven+MyBatis注解
- SpringBoot集成MyBatis的分页插件PageHelper(回头草)
- SpringBoot + Mybatis + Mapper + PageHelper + Spring Batch 整合
- 采用shardbatis在springBoot中实现表的水平拆分,整合swagger,mybatis,shardbatis,pagehelper
- springboot微服务搭建(一):整合mybatis配置(第一种方式)