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

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

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

2.pom里引入druid依赖

        <!-- 分页插件 -->
        <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

#配置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打包编译时会自动编译当前环境配置文件:

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

#############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

#########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属性:

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


/**
 * @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,整合完成!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值