解决方案 »

  1.   

    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
      

  2.   

    只重写determineCurrentLookupKey 这个方法,其它的都去掉
      

  3.   

    http://lyunabc.iteye.com/blog/1544423看下,对你的问题也许有帮助。
      

  4.   

    首先判断在单数据源的时候是否可以正常启动?在但数据源的时候可以正常启动的话,在此基础上改造多数据源;你现在这种写法主要适合于已经固定的数据源,也即是数据源是可预知的;就看你写的基本上是这么回事儿,出问题的跟踪调试;1:把 你spring配置文件中,数据源配置中的 “init-method 是否是必须的呢?可否去掉?2:ContextHolder 这个类里需要指定下数据源,也就是你在配置文件中写的ref的数据源的名称public static final String DATA_SOURCE_A = "dataSource1";  
        
        public static final String DATA_SOURCE_B = "dataSource2";  3:如何切换?如何切换是根据实际情况来定的,写个过滤器,根据登录或者请求不同路径下面的页面来判断调用哪一个数据库;ContextHolder.setDbType(ContextHolder.DATA_SOURCE_A);
    ContextHolder.setDbType(ContextHolder.DATA_SOURCE_B);根据符合条件的来进行切换。
    --------------