018-05-09 02:43:59.669 |-INFO [localhost-startStop-17] org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer [101] -|
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2018-05-09 02:43:59.674 |-ERROR [localhost-startStop-17] org.springframework.boot.SpringApplication [815] -| Application startup failed
org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean [{
CreateTime:"2018-05-09 02:43:51",
ActiveCount:0,
PoolingCount:1,
CreateCount:1,
DestroyCount:0,
CloseCount:3,
ConnectCount:3,
Connections:[
{ID:878203604, ConnectTime:"2018-05-09 02:43:54", UseCount:3, LastActiveTime:"2018-05-09 02:43:55"}
]
}] with key 'ruidDataSourceBean'; nested exception is javax.management.InstanceAlreadyExistsException: com.alibaba.druid.pool:name=ruidDataSourceBean,type=DruidDataSource
1.初始化类
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import com.alibaba.druid.pool.DruidDataSource;
@Configuration
@Profile({"dev", "prod"})
public class DataSourceConfig{
/**
*
*/
private static final long serialVersionUID = 1L;
public static long getSerialversionuid() {
return serialVersionUID;
}
Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);
@Value("${spring.datasource.driver}")
String driverClassName;
@Value("${spring.datasource.url}")
String url;
@Value("${spring.datasource.username}")
String username;
@Value("${spring.datasource.password}")
String password;
@Bean(initMethod="init",destroyMethod="close",name="dataSource")
public DruidDataSource ruidDataSourceBean (){
logger.info("-------------------init alibaba datasource config-------------------------");
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(driverClassName);
druidDataSource.setUrl(url);
druidDataSource.setUsername(username);
druidDataSource.setPassword(password);
logger.info("-------------------init alibaba datasource config done-------------------------");
return druidDataSource;
}
// <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
// init-method="init" destroy-method="close">
// <property name="driverClassName" value="${jdbc.driverClassName}" />
// <property name="url" value="${jdbc.url}" />
// <property name="username" value="${jdbc.username}" />
// <property name="password" value="${jdbc.password}" />
// <!-- 配置初始化大小、最小、最大 -->
// <property name="initialSize" value="1" />
// <property name="minIdle" value="1" />
// <property name="maxActive" value="10" />
//
// <!-- 配置获取连接等待超时的时间 -->
// <property name="maxWait" value="10000" />
//
// <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
// <property name="timeBetweenEvictionRunsMillis" value="60000" />
//
// <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
// <property name="minEvictableIdleTimeMillis" value="300000" />
//
// <property name="testWhileIdle" value="true" />
//
// <!-- 这里建议配置为TRUE,防止取到的连接不可用 -->
// <property name="testOnBorrow" value="true" />
// <property name="testOnReturn" value="false" />
//
// <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
// <property name="poolPreparedStatements" value="true" />
// <property name="maxPoolPreparedStatementPerConnectionSize"
// value="20" />
//
// <!-- 这里配置提交方式,默认就是TRUE,可以不用配置 -->
//
// <property name="defaultAutoCommit" value="true" />
//
// <!-- 验证连接有效与否的SQL,不同的数据配置不同 -->
// <property name="validationQuery" value="select 1 " />
// <property name="filters" value="stat" />
// <property name="proxyFilters">
// <list>
// <ref bean="logFilter" />
// </list>
// </property>
// </bean>
//
//
//
// <bean id="logFilter" class="com.alibaba.druid.filter.logging.Slf4jLogFilter">
// <property name="statementExecutableSqlLogEnable" value="false" />
// </bean>
//
// </beans>
}
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
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.alibaba.druid.pool.DruidDataSource;
/**
* 上面代码创建了一个SqlSessionFactory和一个SqlSessionTemplate,为了支持注解事务,增加了@EnableTransactionManagement注解,
* 并且反回了一个PlatformTransactionManagerBean。
* @author Administrator
*
*/
@Configuration
@EnableTransactionManagement
@AutoConfigureAfter(DataSourceConfig.class)
public class MyBatisConfig implements TransactionManagementConfigurer{
//使用默认数据源
//@Autowired
//DataSource dataSource;
//使用alibaba数据源
@Autowired
@Qualifier("dataSource")
DruidDataSource dataSource;
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
// bean.setTypeAliasesPackage("tk.mybatis.springboot.model");
// //分页插件
// PageHelper pageHelper = new PageHelper();
// Properties properties = new Properties();
// properties.setProperty("reasonable", "true");
// properties.setProperty("supportMethodsArguments", "true");
// properties.setProperty("returnPageInfo", "check");
// properties.setProperty("params", "count=countSql");
// pageHelper.setProperties(properties);
//
// //添加插件
// bean.setPlugins(new Interceptor[]{pageHelper});
//添加XML目录
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
bean.setMapperLocations(resolver.getResources("classpath:com/**/dao/*Mapper.xml"));
return bean.getObject();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
@Configuration
//TODO 注意,由于MapperScannerConfigurer执行的比较早,所以必须有下面的注解
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePackage("com.sstech.module.**.dao");
return mapperScannerConfigurer;
}
}
3.注意
放在服务器上不知道为什么,服务器加载configration的方式哪里和我机器上的不一样。现象是mybatis在找datasource时找不到。于是手动按名称去指定
public class DataSourceConfig{
@Bean(initMethod="init",destroyMethod="close",name="dataSource")
//使用alibaba数据源
@Autowired
@Qualifier("dataSource")
DruidDataSource dataSource;