67,515
社区成员
发帖
与我相关
我的任务
分享
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
">
<!-- 引入属性文件 -->
<context:property-placeholder location="classpath:config/config.properties" />
<!-- 配置数据源 -->
<bean name="dataSource1" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" />
</bean>
<!-- 配置数据源 -->
<bean name="dataSource2" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url2}" />
<property name="username" value="${jdbc_username2}" />
<property name="password" value="${jdbc_password2}" />
</bean>
<bean id="dynamicDataSource" class="com.sa.controller.DynamicDataSource" >
<!-- 通过key-value的形式来关联数据源 -->
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry value-ref="dataSource1" key="dataSource1"></entry>
<entry value-ref="dataSource2" key="dataSource2"></entry>
</map>
</property>
<property name="defaultTargetDataSource" ref="dataSource1" >
</property>
</bean>
<!-- myBatis文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" abstract="true" lazy-init="true">
<property name="dataSource" ref="dynamicDataSource" />
<property name="configLocation" value="classpath:config/mybatis-plugin.xml" />
<property name="mapperLocations" value="classpath:mapper/*.xml" />
</bean>
<!-- SqlSessionTemplate -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype">
<constructor-arg index="0" ref="dynamicDataSource" />
<constructor-arg index="1" value="BATCH" /> <!-- 如果想要进行批量操作可加入这个属性 -->
</bean>
<!--<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> -->
<!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> -->
<!--</bean> -->
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dynamicDataSource" />
</bean>
</beans>
package com.sa.controller;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.jdbc.datasource.lookup.DataSourceLookup;
public class DynamicDataSource extends AbstractRoutingDataSource {
public static final Logger logger = Logger.getLogger(DynamicDataSource.class.toString());
@Override
protected Object determineCurrentLookupKey() {
String name = ContextHolder.getDbType();
System.out.println("当前数据源 :" + name);
return name;
}
@Override
public void setTargetDataSources(Map targetDataSources) {
super.setTargetDataSources(targetDataSources);
//重点
super.afterPropertiesSet();
}
@Override
public void setDataSourceLookup(DataSourceLookup dataSourceLookup) {
super.setDataSourceLookup(dataSourceLookup);
}
@Override
public void setDefaultTargetDataSource(Object defaultTargetDataSource) {
super.setDefaultTargetDataSource(defaultTargetDataSource);
}
}
package com.sa.controller;
public class ContextHolder {
private static final ThreadLocal<Object> holder = new ThreadLocal<Object>();
public static void setDbType(String dbType) {
holder.set(dbType);
}
public static String getDbType() {
return (String) holder.get();
}
public static void clearDbType() {
holder.remove();
}
}
[INFO] [2014-10-16 11:26:44] [Root WebApplicationContext: initialization started]
[INFO] [2014-10-16 11:26:44] [Refreshing Root WebApplicationContext: startup date [Thu Oct 16 11:26:44 CST 2014]; root of context hierarchy]
[INFO] [2014-10-16 11:26:44] [Loading XML bean definitions from class path resource [config/spring.xml]]
[INFO] [2014-10-16 11:26:45] [Loading properties file from class path resource [config/config.properties]]
[INFO] [2014-10-16 11:26:45] [Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1b1a772d: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource1,dataSource2,dynamicDataSource,sqlSessionFactory,sqlSession,transactionManager]; root of factory hierarchy]
[ERROR] [2014-10-16 11:26:45] [testWhileIdle is true, validationQuery not set]
[INFO] [2014-10-16 11:26:45] [{dataSource-1} inited]
[ERROR] [2014-10-16 11:26:45] [testWhileIdle is true, validationQuery not set]
[INFO] [2014-10-16 11:26:45] [{dataSource-2} inited]
[INFO] [2014-10-16 11:26:45] [Root WebApplicationContext: initialization completed in 1490 ms]
2014-10-16 11:26:45 org.apache.catalina.core.ApplicationContext log
信息: Initializing Spring FrameworkServlet 'springMvc'
[INFO] [2014-10-16 11:26:45] [FrameworkServlet 'springMvc': initialization started]
[INFO] [2014-10-16 11:26:45] [Refreshing WebApplicationContext for namespace 'springMvc-servlet': startup date [Thu Oct 16 11:26:45 CST 2014]; parent: Root WebApplicationContext]
[INFO] [2014-10-16 11:26:45] [Loading XML bean definitions from class path resource [config/spring-mvc.xml]]
ERROR] [2014-10-16 11:26:47] [Context initialization failed]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dynamicDataSource' defined in file [E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\saweb_20141012\WEB-INF\classes\com\sa\controller\DynamicDataSource.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'targetDataSources' is required
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1512)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
package com.sa.controller;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
public static final Logger logger = Logger.getLogger(DynamicDataSource.class.toString());
@Override
protected Object determineCurrentLookupKey() {
String name = DBContextHolder.getDBType();
System.out.println("当前数据源 :" + name);
return name;
}
@Override
public void setTargetDataSources(Map targetDataSources) {
System.out.println("初始化"+targetDataSources+"数据源信息");
super.setTargetDataSources(targetDataSources);
//重点
// super.afterPropertiesSet();
}
}
[INFO] [2014-10-16 13:54:25] [Root WebApplicationContext: initialization started]
[INFO] [2014-10-16 13:54:25] [Refreshing Root WebApplicationContext: startup date [Thu Oct 16 13:54:25 CST 2014]; root of context hierarchy]
[INFO] [2014-10-16 13:54:25] [Loading XML bean definitions from class path resource [config/spring.xml]]
[INFO] [2014-10-16 13:54:26] [Loading properties file from class path resource [config/config.properties]]
[INFO] [2014-10-16 13:54:26] [Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6e62be97: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource1,dataSource2,dynamicDataSource,sqlSessionFactory,sqlSession,transactionManager]; root of factory hierarchy]
[ERROR] [2014-10-16 13:54:26] [testWhileIdle is true, validationQuery not set]
[INFO] [2014-10-16 13:54:26] [{dataSource-1} inited]
[ERROR] [2014-10-16 13:54:26] [testWhileIdle is true, validationQuery not set]
[INFO] [2014-10-16 13:54:26] [{dataSource-2} inited]
初始化{dataSource1={
CreateTime:"2014-10-16 13:54:26",
ActiveCount:0,
PoolingCount:0,
CreateCount:0,
DestroyCount:0,
CloseCount:0,
ConnectCount:0,
Connections:[
]
}, dataSource2={
CreateTime:"2014-10-16 13:54:26",
ActiveCount:0,
PoolingCount:0,
CreateCount:0,
DestroyCount:0,
CloseCount:0,
ConnectCount:0,
Connections:[
]
}}数据源信息
[INFO] [2014-10-16 13:54:26] [Root WebApplicationContext: initialization completed in 645 ms]
2014-10-16 13:54:26 org.apache.catalina.core.ApplicationContext log
信息: Initializing Spring FrameworkServlet 'springMvc'
[INFO] [2014-10-16 13:54:26] [FrameworkServlet 'springMvc': initialization started]
[INFO] [2014-10-16 13:54:26] [Refreshing WebApplicationContext for namespace 'springMvc-servlet': startup date [Thu Oct 16 13:54:26 CST 2014]; parent: Root WebApplicationContext]
[INFO] [2014-10-16 13:54:26] [Loading XML bean definitions from class path resource [config/spring-mvc.xml]]
[INFO] [2014-10-16 13:54:26] [Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@ca8e2b8: defining beans [userController,userService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,baseDao,DBContextHolder,dynamicDataSource,org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,mappingJacksonHttpMessageConverter,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,mvcContentNegotiationManager,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.view.InternalResourceViewResolver#0,multipartResolver,exceptionResolver,druid-stat-interceptor,org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator#0,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@6e62be97]
[INFO] [2014-10-16 13:54:27] [Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@ca8e2b8: defining beans [userController,userService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,baseDao,DBContextHolder,dynamicDataSource,org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,mappingJacksonHttpMessageConverter,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,mvcContentNegotiationManager,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.view.InternalResourceViewResolver#0,multipartResolver,exceptionResolver,druid-stat-interceptor,org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator#0,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@6e62be97]
2014-10-16 13:54:27 org.apache.catalina.core.ApplicationContext log
严重: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dynamicDataSource' defined in file [E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\saweb_20141012\WEB-INF\classes\com\sa\controller\DynamicDataSource.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'targetDataSources' is required
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1512)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.spri