spring 多数据源出错,好像是属性没有注入进去?大神帮忙看看,在线等。。。 <?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> 继承 import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource 的类 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) 主要 就是[Context initialization failed] |
|
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 |
|
10分 |
只重写determineCurrentLookupKey 这个方法,其它的都去掉
|
10分 |
http://lyunabc.iteye.com/blog/1544423
看下,对你的问题也许有帮助。 |
80分 |
首先判断在单数据源的时候是否可以正常启动?
在但数据源的时候可以正常启动的话,在此基础上改造多数据源;你现在这种写法主要适合于已经固定的数据源,也即是数据源是可预知的; 就看你写的基本上是这么回事儿,出问题的跟踪调试; 1:把 你spring配置文件中,数据源配置中的 “init-method 是否是必须的呢?可否去掉? 2: ContextHolder? 这个类里需要指定下数据源,也就是你在配置文件中写的ref的数据源的名称 public static final String DATA_SOURCE_A = “dataSource1”; 3:如何切换? 如何切换是根据实际情况来定的,写个过滤器,根据登录或者请求不同路径下面的页面来判断调用哪一个数据库; ContextHolder.setDbType(ContextHolder.DATA_SOURCE_A); 根据符合条件的来进行切换。 |