Skip to content

Instantly share code, notes, and snippets.

@ilaotan
Created November 7, 2016 10:57
Show Gist options
  • Save ilaotan/51e0cde58fbb9b38e3b29cf8b9e13627 to your computer and use it in GitHub Desktop.
Save ilaotan/51e0cde58fbb9b38e3b29cf8b9e13627 to your computer and use it in GitHub Desktop.
以下配置在springboot-1.4.1下测试通过
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
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.boot.autoconfigure.condition.ConditionalOnClass;
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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;
/**
* Created by tan on 2016/10/24.
*/
@Configuration
@ConditionalOnClass(com.mysql.jdbc.Driver.class)
@EnableTransactionManagement
public class MybatisConfiguration implements EnvironmentAware {
private RelaxedPropertyResolver propertyResolver;
private String driveClassName;
private String url;
private String userName;
private String password;
private String xmlLocation;
private String typeAliasesPackage;
/////////////////////druid参数///////////////////////////////////////////////////
private String filters;
private String maxActive;
private String initialSize;
private String maxWait;
private String minIdle;
private String timeBetweenEvictionRunsMillis;
private String minEvictableIdleTimeMillis;
private String validationQuery;
private String testWhileIdle;
private String testOnBorrow;
private String testOnReturn;
private String poolPreparedStatements;
private String maxOpenPreparedStatements;
//////////////////////////////////////////////////////////////////////////
@Bean(name = "sqlSessionFactory")
@ConditionalOnClass(com.mysql.jdbc.Driver.class)
public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
if(StringUtils.isNotBlank(typeAliasesPackage)){
bean.setTypeAliasesPackage(typeAliasesPackage);
}
//分页插件
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("offsetAsPageNum", "true");
properties.setProperty("rowBoundsWithCount", "true");
properties.setProperty("pageSizeZero", "true");
properties.setProperty("reasonable", "false");
properties.setProperty("params", "pageNum=pageHelperStart;pageSize=pageHelperRows;");
properties.setProperty("supportMethodsArguments", "false");
properties.setProperty("returnPageInfo", "none");
pageHelper.setProperties(properties);
//添加插件
bean.setPlugins(new Interceptor[]{pageHelper});
//添加XML目录
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
bean.setMapperLocations(resolver.getResources(xmlLocation));
return bean.getObject();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Bean
@ConditionalOnClass(com.mysql.jdbc.Driver.class)
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
@Bean
@ConditionalOnClass(com.mysql.jdbc.Driver.class)
public ServletRegistrationBean druidServlet() {
ServletRegistrationBean reg = new ServletRegistrationBean();
reg.setServlet(new StatViewServlet());
reg.addUrlMappings("/druid/*");
//reg.addInitParameter("allow", "127.0.0.1");
//reg.addInitParameter("deny","");
reg.addInitParameter("loginUsername", "admin");
reg.addInitParameter("loginPassword", "admin456");
return reg;
// return new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
}
@Bean
@ConditionalOnClass(com.mysql.jdbc.Driver.class)
public DataSource druidDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl(url);
druidDataSource.setUsername(userName);
druidDataSource.setPassword(password);
druidDataSource.setDriverClassName(StringUtils.isNotBlank(driveClassName)?driveClassName:"com.mysql.jdbc.Driver");
druidDataSource.setMaxActive(StringUtils.isNotBlank(maxActive)? Integer.parseInt(maxActive):10);
druidDataSource.setInitialSize(StringUtils.isNotBlank(initialSize)? Integer.parseInt(initialSize):1);
druidDataSource.setMaxWait(StringUtils.isNotBlank(maxWait)? Integer.parseInt(maxWait):60000);
druidDataSource.setMinIdle(StringUtils.isNotBlank(minIdle)? Integer.parseInt(minIdle):3);
druidDataSource.setTimeBetweenEvictionRunsMillis(StringUtils.isNotBlank(timeBetweenEvictionRunsMillis)?
Integer.parseInt(timeBetweenEvictionRunsMillis):60000);
druidDataSource.setMinEvictableIdleTimeMillis(StringUtils.isNotBlank(minEvictableIdleTimeMillis)?
Integer.parseInt(minEvictableIdleTimeMillis):300000);
druidDataSource.setValidationQuery(StringUtils.isNotBlank(validationQuery)?validationQuery:"select 'x'");
druidDataSource.setTestWhileIdle(StringUtils.isNotBlank(testWhileIdle)? Boolean.parseBoolean(testWhileIdle):true);
druidDataSource.setTestOnBorrow(StringUtils.isNotBlank(testOnBorrow)? Boolean.parseBoolean(testOnBorrow):false);
druidDataSource.setTestOnReturn(StringUtils.isNotBlank(testOnReturn)? Boolean.parseBoolean(testOnReturn):false);
druidDataSource.setPoolPreparedStatements(StringUtils.isNotBlank(poolPreparedStatements)? Boolean.parseBoolean(poolPreparedStatements):true);
druidDataSource.setMaxOpenPreparedStatements(StringUtils.isNotBlank(maxOpenPreparedStatements)? Integer.parseInt(maxOpenPreparedStatements):20);
try {
druidDataSource.setFilters(StringUtils.isNotBlank(filters)?filters:"stat, wall");
} catch (SQLException e) {
e.printStackTrace();
}
return druidDataSource;
}
@Bean
@ConditionalOnClass(com.mysql.jdbc.Driver.class)
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
@Override
public void setEnvironment(Environment environment) {
// this.propertyResolver = new RelaxedPropertyResolver(environment, "spring.datasource.");
this.propertyResolver = new RelaxedPropertyResolver(environment, null);
this.url = propertyResolver.getProperty("spring.datasource.url");
this.userName= propertyResolver.getProperty("spring.datasource.username");
this.password = propertyResolver.getProperty("spring.datasource.password");
this.driveClassName = propertyResolver.getProperty("spring.datasource.driver-class-name");
this.filters = propertyResolver.getProperty("spring.datasource.filters");
this.maxActive = propertyResolver.getProperty("spring.datasource.maxActive");
this.initialSize = propertyResolver.getProperty("spring.datasource.initialSize");
this.maxWait = propertyResolver.getProperty("spring.datasource.maxWait");
this.minIdle = propertyResolver.getProperty("spring.datasource.minIdle");
this.timeBetweenEvictionRunsMillis = propertyResolver.getProperty("spring.datasource.timeBetweenEvictionRunsMillis");
this.minEvictableIdleTimeMillis = propertyResolver.getProperty("spring.datasource.minEvictableIdleTimeMillis");
this.validationQuery = propertyResolver.getProperty("spring.datasource.validationQuery");
this.testWhileIdle = propertyResolver.getProperty("spring.datasource.testWhileIdle");
this.testOnBorrow = propertyResolver.getProperty("spring.datasource.testOnBorrow");
this.testOnReturn = propertyResolver.getProperty("spring.datasource.testOnReturn");
this.poolPreparedStatements = propertyResolver.getProperty("spring.datasource.poolPreparedStatements");
this.maxOpenPreparedStatements = propertyResolver.getProperty("spring.datasource.maxOpenPreparedStatements");
this.typeAliasesPackage = propertyResolver.getProperty("mybatis.typeAliasesPackage");
this.xmlLocation = propertyResolver.getProperty("mybatis.xmlLocation");
}
@Bean
public DataSourceTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;
import java.util.Properties;
/**
*
*/
@Configuration
@AutoConfigureAfter(MybatisConfiguration.class)
@ConditionalOnClass(com.mysql.jdbc.Driver.class)
public class MapperConfiguration implements EnvironmentAware {
private RelaxedPropertyResolver propertyResolver;
private String basePackage;
@Bean
@ConditionalOnClass(com.mysql.jdbc.Driver.class)
public MapperScannerConfigurer mapperScannerConfigurer(Environment environment){
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setMarkerInterface(MyMapper.class);
mapperScannerConfigurer.setBasePackage(basePackage);
Properties properties = new Properties();
// properties.setProperty("mappers", "com.xxxx.framework.config.MyMapper");
properties.setProperty("notEmpty", "false");
properties.setProperty("IDENTITY", "MYSQL");
mapperScannerConfigurer.setProperties(properties);
return mapperScannerConfigurer;
}
@Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment, null);
this.basePackage = propertyResolver.getProperty("mybatis.basepackage");
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
类中的Property参数都是在application.properties(application.yml)里的:
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
#######################可更改##################################
mybatis.basepackage=com.xxxx.common.repositories.mappers
mybatis.xmlLocation=classpath:mapper/**/*.xml
#选填,若需要就写上 否则 注释掉
mybatis.typeAliasesPackage=com.xxxx.common.models
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment