项目源码路径:http://download.csdn.net/download/a295277302/9936886
pom.xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.1.0</version> </dependency>application.properties
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.url=jdbc:mysql://localhost:3306/mybatis spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver # 下面为连接池的补充设置,应用到上面所有数据源中 # 初始化大小,最小,最大 spring.datasource.initialSize=5 spring.datasource.minIdle=5 spring.datasource.maxActive=20 # 配置获取连接等待超时的时间 spring.datasource.maxWait=60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 spring.datasource.timeBetweenEvictionRunsMillis=60000 # 配置一个连接在池中最小生存的时间,单位是毫秒 spring.datasource.minEvictableIdleTimeMillis=300000 spring.datasource.validationQuery=SELECT 1 FROM DUAL spring.datasource.testWhileIdle=true spring.datasource.testOnBorrow=false spring.datasource.testOnReturn=false # 打开PSCache,并且指定每个连接上PSCache的大小 spring.datasource.poolPreparedStatements=true spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 spring.datasource.filters=stat,wall,log4j # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 # 合并多个DruidDataSource的监控数据 #spring.datasource.useGlobalDataSourceStat=true spring.thymeleaf.cache = false spring.thymeleaf.mode = LEGACYHTML5 server.port = 9000 spring.application.name = htf admin spring.application.ip = localhost #logging.config= # location of config file (default classpath:logback.xml for logback) logging.file=dashboard.log logging.level.*=INFO logging.level.com.htf=DEBUG mybatis.type-aliases-package=com.htf.entity
DruidDataSourceConfig
package com.htf.config; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import com.alibaba.druid.support.spring.stat.DruidStatInterceptor; import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; /** * *Druid的DataResource配置类 * 凡是被Spring管理的类,实现接口 EnvironmentAware 重写方法 setEnvironment 可以在工程启动时,先启动 * 获取到系统环境变量和application配置文件中的变量。 还有一种方式是采用注解的方式获取 @value("${变量的key值}") * 获取application配置文件中的变量。 这里采用第一种要方便些 * Created by PC-FENG on 2017/8/16. */ @Configuration @EnableTransactionManagement public class DruidDataSourceConfig implements EnvironmentAware { private RelaxedPropertyResolver propertyResolver; public void setEnvironment(Environment env) { this.propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource."); } @Bean public DataSource dataSource() { DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(propertyResolver.getProperty("url")); datasource.setDriverClassName(propertyResolver.getProperty("driver-class-name")); datasource.setUsername(propertyResolver.getProperty("username")); datasource.setPassword(propertyResolver.getProperty("password")); datasource.setInitialSize(Integer.valueOf(propertyResolver.getProperty("initialSize"))); datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("minIdle"))); datasource.setMaxWait(Long.valueOf(propertyResolver.getProperty("maxWait"))); datasource.setMaxActive(Integer.valueOf(propertyResolver.getProperty("maxActive"))); datasource.setMinEvictableIdleTimeMillis( Long.valueOf(propertyResolver.getProperty("minEvictableIdleTimeMillis"))); try { datasource.setFilters("stat,wall"); } catch (SQLException e) { e.printStackTrace(); } return datasource; } @Bean public ServletRegistrationBean druidServlet() { ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(); servletRegistrationBean.setServlet(new StatViewServlet()); servletRegistrationBean.addUrlMappings("/druid/*"); Map<String, String> initParameters = new HashMap<String, String>(); // initParameters.put("loginUsername", "druid");// 用户名 // initParameters.put("loginPassword", "druid");// 密码 initParameters.put("resetEnable", "false");// 禁用HTML页面上的“Reset All”功能 initParameters.put("allow", "127.0.0.1"); // IP白名单 (没有配置或者为空,则允许所有访问) // initParameters.put("deny", "192.168.20.38");// IP黑名单 // (存在共同时,deny优先于allow) servletRegistrationBean.setInitParameters(initParameters); return servletRegistrationBean; } @Bean public FilterRegistrationBean filterRegistrationBean() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new WebStatFilter()); filterRegistrationBean.addUrlPatterns("/*"); filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"); return filterRegistrationBean; } // 按照BeanId来拦截配置 用来bean的监控 @Bean(value = "druid-stat-interceptor") public DruidStatInterceptor DruidStatInterceptor() { DruidStatInterceptor druidStatInterceptor = new DruidStatInterceptor(); return druidStatInterceptor; } @Bean public BeanNameAutoProxyCreator beanNameAutoProxyCreator() { BeanNameAutoProxyCreator beanNameAutoProxyCreator = new BeanNameAutoProxyCreator(); beanNameAutoProxyCreator.setProxyTargetClass(true); // 设置要监控的bean的id //beanNameAutoProxyCreator.setBeanNames("sysRoleMapper","loginController"); beanNameAutoProxyCreator.setInterceptorNames("druid-stat-interceptor"); return beanNameAutoProxyCreator; } }
MyBatisConfiguration
package com.htf.config; import java.util.Properties; import javax.sql.DataSource; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.TransactionManagementConfigurer; import com.github.pagehelper.PageHelper; /** * Created by PC-FENG on 2017/8/16. */ @Configuration //加上这个注解,使得支持事务 @EnableTransactionManagement public class MyBatisConfiguration implements TransactionManagementConfigurer{ @Autowired DataSource dataSource; @Bean(name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactoryBean() { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); //分页插件 PageHelper pageHelper = new PageHelper(); Properties props = new Properties(); props.setProperty("reasonable", "true"); props.setProperty("supportMethodsArguments", "true"); props.setProperty("returnPageInfo", "check"); props.setProperty("params", "count=countSql"); pageHelper.setProperties(props); //添加插件 bean.setPlugins(new Interceptor[]{pageHelper}); try { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); bean.setConfigLocation(resolver.getResource("classpath:mybatis-config.xml")); return bean.getObject(); } catch (Exception e) { e.printStackTrace(); return null; } } @Bean public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } @Bean @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return new DataSourceTransactionManager(dataSource); } }之后访问http://localhost:9000/druid/datasource.html