编程开发 购物 网址 游戏 小说 歌词 快照 开发 股票 美女 新闻 笑话 | 汉字 软件 日历 阅读 下载 图书馆 编程 China
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
移动开发 架构设计 编程语言 互联网 开发经验 Web前端 开发总结
开发杂谈 系统运维 研发管理 数据库 云 计 算 Java开发
VC(MFC) Delphi VB C++(C语言) C++ Builder 其它开发语言 云计算 Java开发 .Net开发 IOS开发 Android开发 PHP语言 JavaScript
ASP语言 HTML(CSS) HTML5 Apache MSSQL数据库 Oracle数据库 PowerBuilder Informatica 其它数据库 硬件及嵌入式开发 Linux开发资料
  编程开发知识库 -> 开发杂谈 -> 使用注解配置实现Spring动态数据源切换 -> 正文阅读
 

[开发杂谈]使用注解配置实现Spring动态数据源切换[第1页]


使用注解配置实现Spring动态数据源切换,详细说明:
一、实现原理
1、自定义动态数据源类 com.any.datasource.DynamicDataSource:
实现org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource的方法determineCurrentLookupKey
2、自定义Spring AOP类 com.any.aspect.DataSourceAspect
3、自定义注解类 com.any.annotation.DataSource
测试环境eclipse+spring+restlet+mysql 
二、代码实现:
1、com.any.annotation.DataSource
package com.any.annotation;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


/**
 * 数据源名称注解类
 * @author danny
 * @version 1.0 2016-5-10
 */
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSource {
    String value();
}

2、com.any.aspect.DataSourceAspect
package com.any.aspect;


import java.lang.reflect.Method;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;


import com.any.annotation.DataSource;
import com.any.datasource.DynamicDataSourceHolder;




/**
 * AOP类根据注解com.any.annotation.DataSource的数据源名称
 * 更新数据源DynamicDataSourceHolder.setDataSource(..)
 * 
 * @author danny
 * @version 1.0 2016-5-10
 */
public class DataSourceAspect {


    /**
     * 拦截目标方法,获取由@DataSource指定的数据源标识,设置到线程存储中以便切换数据源
     * 
     * @param point
     * @throws Exception
     */
    public void interceptMethod(JoinPoint point) throws Exception {
        Class<?> target = point.getTarget().getClass();
        MethodSignature signature = (MethodSignature) point.getSignature();
        // 默认使用目标类型的注解,如果没有则使用其实现接口的注解类
        for (Class<?> cls : target.getInterfaces()) {
            resetDataSource(cls, signature.getMethod());
        }
        resetDataSource(target, signature.getMethod());
    }


    /**
     * 提取目标对象方法注解和类注解中的数据源标识
     * 
     * @param cla
     * @param method
     */
    private void resetDataSource(Class<?> cls, Method method) {
        try {
            Class<?>[] types = method.getParameterTypes();
            // 默认使用类注解
            if (cls.isAnnotationPresent(DataSource.class)) {
                DataSource source = cls.getAnnotation(DataSource.class);
                DynamicDataSourceHolder.setDataSource(source.value());
                System.out.println("class source.value()="+source.value());
            }
            // 方法注解可以覆盖类注解
            Method m = cls.getMethod(method.getName(), types);
            if (m != null && m.isAnnotationPresent(DataSource.class)) {
                DataSource source = m.getAnnotation(DataSource.class);
                System.out.println("method source.value()="+source.value());
                DynamicDataSourceHolder.setDataSource(source.value());
            }
        } catch (Exception e) {
            System.out.println(cls + ":" + e.getMessage());
        }
    }


}

3、com.any.datasource.DynamicDataSource
package com.any.datasource;


import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;


/**
 * 动态数据源
 * 实现spring 类方法AbstractRoutingDataSource.determineCurrentLookupKey
 * 以更新数据源bean
 * @author danny
 * @version 1.0 2016-5-10
 */
public class DynamicDataSource extends AbstractRoutingDataSource {


    @Override
    protected Object determineCurrentLookupKey() {
        // 获取数据源标识
        return DynamicDataSourceHolder.getDataSource();
    }


}
4、com.any.datasource.DynamicDataSourceHolder
package com.any.datasource;
/**
 * 动态数据源标识更新
 * @author danny
 * @version 1.0 2016-5-10
 */
public class DynamicDataSourceHolder {


    public DynamicDataSourceHolder() {
        // TODO Auto-generated constructor stub
    }
    /**
     * 数据源标识保存在线程变量中,避免多线程操作数据源时互相干扰
     */
   private static final ThreadLocal<String> THREAD_DATA_SOURCE = new ThreadLocal<String>();


   public static String getDataSource() {
       return THREAD_DATA_SOURCE.get();
   }


   public static void setDataSource(String dataSource) {
       THREAD_DATA_SOURCE.set(dataSource);
   }


   public static void clearDataSource() {
       THREAD_DATA_SOURCE.remove();
   }
}

5、com.any.entity.PersonEntity
package com.any.entity;


/**
 * @author danny
 * @version 1.0 2016-5-10
 */
public class PersonEntity {
    private String id;
    private String userName;
    private String age;


    public String getId() {
        return id;
    }


    public void setId(String id) {
        this.id = id;
    }


    public String getUserName() {
        return userName;
    }


    public void setUserName(String userName) {
        this.userName = userName;
    }


    public String getAge() {
        return age;
    }


    public void setAge(String age) {
        this.age = age;
    }


}

6、com.any.entrance.IPersonResource
package com.any.entrance;


import java.util.List;


import org.restlet.resource.Get;


import com.any.entity.PersonEntity;


/**
 * @author danny
 * @version 1.0 2016-5-10
 */
public interface IPersonResource
{
    @Get("json")
    public List<PersonEntity>  getPersons();
}

7、com.any.entrance.PersonResource
package com.any.entrance;


import java.util.List;


import javax.annotation.Resource;


import org.restlet.resource.ServerResource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;


import com.any.entity.PersonEntity;
import com.any.service.ResourcePersonService;


/**
 * @author danny
 * @version 1.0 2016-5-10
 */
@Controller
@Scope("prototype")
public class PersonResource extends ServerResource implements IPersonResource
{


    @Resource(name="resourcePersonService")  
    ResourcePersonService resourcePersonService;


    @Override
    public List<PersonEntity> getPersons()
    {   //数据源DataSource1
         return resourcePersonService.getPersons1();
    }
}

8、com.any.entrance.PersonResource2
package com.any.entrance;


import java.util.List;


import javax.annotation.Resource;


import org.restlet.resource.ServerResource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;


import com.any.entity.PersonEntity;
import com.any.service.ResourcePersonService;


/**
 * @author danny
 * @version 1.0 2016-5-10
 */
@Controller
@Scope("prototype")
public class PersonResource2 extends ServerResource implements IPersonResource
{


    @Resource(name="resourcePersonService")  
    ResourcePersonService resourcePersonService;


    @Override
    public List<PersonEntity> getPersons()
    {   //数据源DataSource2
         return resourcePersonService.getPersons2();
    }
}

9、com.any.entrance.PersonResource3
package com.any.entrance;


import java.util.List;


import javax.annotation.Resource;


import org.restlet.resource.ServerResource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;


import com.any.entity.PersonEntity;
import com.any.service.ResourcePersonService;


/**
 * @author danny
 * @version 1.0 2016-5-10
 */
@Controller
@Scope("prototype")
public class PersonResource3 extends ServerResource implements IPersonResource
{


    @Resource(name="resourcePersonService")  
    ResourcePersonService resourcePersonService;


    @Override
    public List<PersonEntity> getPersons()
    {   //数据源DataSource2
         return resourcePersonService.getPersons3();
    }
}

10、com.any.service.ResourcePersonService
package com.any.service;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;


import com.any.annotation.DataSource;
import com.any.entity.PersonEntity;


/**
 * 获取数据service
 * @author danny
 * @version 1.0 2016-5-10
 */
@Service("resourcePersonService")
@DataSource("dataSource1")
public class ResourcePersonService 
{


    @Autowired
    JdbcTemplate mutlJdbcTemplate;


    public List<PersonEntity> getPersons1()
    {
        return getPersons();
    }


    /**
     * @param userName
     * @return
     */
    @DataSource("dataSource2")
    public List<PersonEntity> getPersons2()
    {
        return getPersons();
    }


    @DataSource("dataSource3")
    public List<PersonEntity> getPersons3()
    {
        return getPersons();
    }


    private List<PersonEntity> getPersons(){
        List<PersonEntity> personsList = new ArrayList<PersonEntity>();
        SqlRowSet rs = mutlJdbcTemplate.queryForRowSet( "select id,username,age from person");
        while ( rs.next() )
        {    
              PersonEntity person=new PersonEntity();
              person.setId(rs.getString("id"));
              person.setUserName(rs.getString("username"));
              person.setAge(rs.getString("age"));
              personsList.add(person);
        }


        return personsList;
    }


}

11、application.properties
#\u6570\u636E\u6E901
mysql1.driver=com.mysql.jdbc.Driver
mysql1.url=jdbc:mysql://localhost:3306/ssh1?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=round
mysql1.username=root
mysql1.password=111111
mysql1.initialSize=5
mysql1.maxActive=10
mysql1.maxIdle=10
mysql1.minIdle=5
mysql1.removeAbandoned=true
mysql1.removeAbandonedTimeout=15000
mysql1.maxWait=15000


#\u6570\u636E\u6E902
mysql2.driver=com.mysql.jdbc.Driver
mysql2.url=jdbc:mysql://localhost:3306/ssh2?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=round
mysql2.username=root
mysql2.password=111111
mysql2.initialSize=5
mysql2.maxActive=10
mysql2.maxIdle=10
mysql2.minIdle=5
mysql2.removeAbandoned=true
mysql2.removeAbandonedTimeout=15000
mysql2.maxWait=15000


#\u6570\u636E\u6E903
mysql3.driver=com.mysql.jdbc.Driver
mysql3.url=jdbc:mysql://localhost:3306/ssh3?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=round
mysql3.username=root
mysql3.password=111111
mysql3.initialSize=5
mysql3.maxActive=10
mysql3.maxIdle=10
mysql3.minIdle=5
mysql3.removeAbandoned=true
mysql3.removeAbandonedTimeout=15000
mysql3.maxWait=15000

13、multDS-context.xml
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    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/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">


 <!--创建数据源1,连接数据库ssh1 -->
 <bean id="dataSource1" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName">
            <value>${mysql1.driver}</value>
        </property>
        <property name="url">
            <value>${mysql1.url}</value>
        </property>
        <property name="username">
            <value>${mysql1.username}</value>
        </property>
        <property name="password">
            <value>${mysql1.password}</value>
        </property>
        <!-- 初始化连接数 -->
        <property name="initialSize">
            <value>${mysql1.initialSize}</value>
        </property>
        <!-- 最大连接数 -->
        <property name="maxActive">
            <value>${mysql1.maxActive}</value>
        </property>
        <!-- 最大空闲连接数 -->
        <property name="maxIdle">
            <value>${mysql1.maxIdle}</value>
        </property>
        <!-- 最小空闲连接数 -->
        <property name="minIdle">
            <value>${mysql1.minIdle}</value>
        </property>
        <!-- 是否自动回收超时连接 -->
        <property name="removeAbandoned">
            <value>${mysql1.removeAbandoned}</value>
        </property>
        <!-- 超时时间 -->
        <property name="removeAbandonedTimeout">
            <value>${mysql1.removeAbandonedTimeout}</value>
        </property>
        <!-- 超时等待时间 -->
        <property name="maxWait">
            <value>${mysql1.maxWait}</value>
        </property>
 </bean>
 <!--创建数据源2,连接数据库ssh2 -->
 <bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName">
            <value>${mysql2.driver}</value>
        </property>
        <property name="url">
            <value>${mysql2.url}</value>
        </property>
        <property name="username">
            <value>${mysql2.username}</value>
        </property>
        <property name="password">
            <value>${mysql2.password}</value>
        </property>
        <!-- 初始化连接数 -->
        <property name="initialSize">
            <value>${mysql2.initialSize}</value>
        </property>
        <!-- 最大连接数 -->
        <property name="maxActive">
            <value>${mysql2.maxActive}</value>
        </property>
        <!-- 最大空闲连接数 -->
        <property name="maxIdle">
            <value>${mysql2.maxIdle}</value>
        </property>
        <!-- 最小空闲连接数 -->
        <property name="minIdle">
            <value>${mysql2.minIdle}</value>
        </property>
        <!-- 是否自动回收超时连接 -->
        <property name="removeAbandoned">
            <value>${mysql2.removeAbandoned}</value>
        </property>
        <!-- 超时时间 -->
        <property name="removeAbandonedTimeout">
            <value>${mysql2.removeAbandonedTimeout}</value>
        </property>
        <!-- 超时等待时间 -->
        <property name="maxWait">
            <value>${mysql2.maxWait}</value>
        </property>
 </bean>
 <!--创建数据源3,连接数据库ssh3 -->
    <!-- MYSQL数据库配置 -->
    <bean id="dataSource3" class="org.apache.commons.dbcp.BasicDataSource" >
        <property name="driverClassName">
            <value>${mysql3.driver}</value>
        </property>
        <property name="url">
            <value>${mysql3.url}</value>
        </property>
        <property name="username">
            <value>${mysql3.username}</value>
        </property>
        <property name="password">
            <value>${mysql3.password}</value>
        </property>
        <!-- 初始化连接数-->
        <property name="initialSize">
            <value>${mysql3.initialSize}</value>
        </property>
        <!-- 最大连接数-->
        <property name="maxActive">
            <value>${mysql3.maxActive}</value>
        </property>
        <!-- 最大空闲连接数-->
        <property name="maxIdle">
            <value>${mysql3.maxIdle}</value>
        </property>
        <!-- 最小空闲连接数-->
        <property name="minIdle">
            <value>${mysql3.minIdle}</value>
        </property>
        <!-- 是否自动回收超时连接-->
        <property name="removeAbandoned">
            <value>${mysql3.removeAbandoned}</value>
        </property>
        <!-- 超时时间-->
        <property name="removeAbandonedTimeout">
            <value>${mysql3.removeAbandonedTimeout}</value>
        </property>
        <!-- 超时等待时间-->
        <property name="maxWait">
            <value>${mysql3.maxWait}</value>
        </property>
        <property name="testOnBorrow">
            <value>true</value>
        </property>
        <property name="testOnReturn">
            <value>true</value>
        </property>
        <property name="testWhileIdle">
            <value>true</value>
        </property>
        <property name="validationQuery">
            <value>select 1 from DUAL</value>
        </property>
    </bean>


     <bean id="dynamicDataSource" class="com.any.datasource.DynamicDataSource">  
         <property name="targetDataSources">  
             <map key-type="java.lang.String">
                 <!-- 指定lookupKey和与之对应的数据源 -->
                 <entry key="dataSource1" value-ref="dataSource1"></entry>  
                 <entry key="dataSource2" value-ref="dataSource2"></entry>  
                 <entry key="dataSource3" value-ref="dataSource3"></entry>  
             </map>  
         </property>  
         <!-- 这里可以指定默认的数据源 -->
         <property name="defaultTargetDataSource" ref="dataSource1" />  
     </bean> 
     <bean id="mutlJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource">
            <ref local="dynamicDataSource" />
        </property>
     </bean>


  <bean id="dataSourceAspect" class="com.any.aspect.DataSourceAspect"/>
  <aop:config proxy-target-class="true">
      <aop:aspect ref="dataSourceAspect">
          <!-- 拦截所有service方法 -->
          <aop:pointcut id="dataSourcePointcut" expression="execution(* com.any.service.ResourcePersonService.*(..))"/>
          <aop:before pointcut-ref="dataSourcePointcut" method="interceptMethod" />
      </aop:aspect>
  </aop:config>
</beans>

14、mysql_dml.sql
drop database if exists ssh1;


drop database if exists ssh2;


drop database if exists ssh3;


create database ssh1;
use ssh1;


CREATE TABLE `person` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) DEFAULT NULL,
  `age` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;




create database ssh2;
use ssh2;


CREATE TABLE `person` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) DEFAULT NULL,
  `age` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;


create database ssh3;
use ssh3;


CREATE TABLE `person` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) DEFAULT NULL,
  `age` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;






insert into ssh1.person
values(1,'a',10),(2,'b',11);
insert into ssh2.person
values(3,'c',10),(4,'d',11);
insert into ssh3.person
values(5,'e',10),(6,'f',11);

15、restlet-context.xml
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    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/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">


    <bean name="application"
          class="org.restlet.Application">
            <property name="inboundRoot">
            <bean class="org.restlet.ext.spring.SpringRouter">
                <constructor-arg ref="application" />
                <property name="attachments">
                <map>
                     <!-- person查询接口dataSource1-->
                    <entry key="/persons1">
                        <bean class="org.restlet.ext.spring.SpringFinder">
                            <lookup-method name="create" bean="personResource" />
                        </bean>
                    </entry>


                     <!-- person查询接口dataSource2 -->
                    <entry key="/persons2">
                        <bean class="org.restlet.ext.spring.SpringFinder">
                            <lookup-method name="create" bean="personResource2" />
                        </bean>
                    </entry>
                     <!-- person查询接口dataSource3-->
                    <entry key="/persons3">
                        <bean class="org.restlet.ext.spring.SpringFinder">
                            <lookup-method name="create" bean="personResource3" />
                        </bean>
                    </entry>  
                </map>
                </property>
            </bean>
        </property>
    </bean>


</beans>

16、applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"
    default-lazy-init="true">


    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
        <property name="ignoreResourceNotFound" value="true" />
        <property name="locations">
            <list>
                <value>classpath*:/application.properties</value>
            </list>
        </property>
    </bean>


    <import resource="classpath*:*-context.xml" />
    <context:component-scan base-package="com.any"/>
</beans>

17、web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Multiple DataSource</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>restlet</servlet-name>
    <servlet-class>org.restlet.ext.spring.SpringServerServlet</servlet-class>
    <init-param>
      <param-name>org.restlet.application</param-name>
      <param-value>application</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>restlet</servlet-name>
    <url-pattern>/resource/*</url-pattern>
  </servlet-mapping>


</web-app>

18、index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Multiple DataSource</title>
<script src="/MultDataSource/js/jquery-2.1.4.min.js"></script>
</head>
<body>


<table id="person1" border="1">
<thead><th colspan="3">数据源1</th></thead>
<tr><td>Id</td><td>userName</td><td>Age</td></tr>
</table>
</br>
<table id="person2" border="1">
<thead><th colspan="3">数据源2</th></thead>
<tr><td>Id</td><td>userName</td><td>Age</td></tr>
</table>
</br>
<table id="person3" border="1">
<thead><th colspan="3">数据源3</th></thead>
<tr><td>Id</td><td>userName</td><td>Age</td></tr>
</table>
</body>
<script type="text/javascript">
$(document).ready(function(){
    //url 对应restlet-context.xml中的key: <entry key="/persons1"></entry>
    $.ajax({
        url:'/MultDataSource/resource/persons1?',
        type:'GET',
        cache : false ,
        dataType:'JSON',
        success:function(data){
            if(data==null){return;}
              for(var i=0;i<data.length;i++){
                  var person = data[i]; 
                  $("#person1").append("<tr><td>"+person.id+"</td><td>"+person.userName+"</td><td>"+person.age+"</td></tr>");
              }
        }
    });
    $.ajax({
        url:'/MultDataSource/resource/persons2?',
        type:'GET',
        cache : false ,
        dataType:'JSON',
        success:function(data){
            if(data==null){return;}
              for(var i=0;i<data.length;i++){
                  var person = data[i]; 
                  $("#person2").append("<tr><td>"+person.id+"</td><td>"+person.userName+"</td><td>"+person.age+"</td></tr>");
              }
        }
    });
    $.ajax({
        url:'/MultDataSource/resource/persons3?',
        type:'GET',
        cache : false ,
        dataType:'JSON',
        success:function(data){
            if(data==null){return;}
              for(var i=0;i<data.length;i++){
                  var person = data[i]; 
                  $("#person3").append("<tr><td>"+person.id+"</td><td>"+person.userName+"</td><td>"+person.age+"</td></tr>");
              }
        }
    });    
});


</script>
</html>

三、实现结果:http://localhost:8080/MultDataSource/



四、源代码eclipse工程
源代码可以从这里下载 http://download.csdn.net/detail/y_xp/9526999
1、eclipse 工程目录结构如下


2、主要配置文件说明:
application.properties:数据源连接属性信息
multDS-context.xml:spring多数据源配置+ spring aop 
mysql_dml.sql : 测试用mysql DML,直接copy 在mysql中执行创建表及样例数据
restlet-context.xml: restlet router配置
applicationContext.xml:spring主配置入口
web.xml:引入spring, restlet 
  开发杂谈 最新文章
centos6 更新glibc-2.14
流水账...12321984543
ros常用工具汇总
我想成为一个真的程序员
KITTI数据集测试
TensorFlow(安装和初使用)
集算报表实现动态显示列
高斯牛顿迭代法
【51nod】第K大区间2(二分+树状数组)
Android自定义View——圆形进度条式按钮
上一篇文章      下一篇文章      查看所有文章
加:2016-05-27 23:53:49  更:2016-05-27 23:59:43 
VC(MFC) Delphi VB C++(C语言) C++ Builder 其它开发语言 云计算 Java开发 .Net开发 IOS开发 Android开发 PHP语言 JavaScript
ASP语言 HTML(CSS) HTML5 Apache MSSQL数据库 Oracle数据库 PowerBuilder Informatica 其它数据库 硬件及嵌入式开发 Linux开发资料
360图书馆 软件开发资料 文字转语音 购物精选 软件下载 新闻资讯 小游戏 Chinese Culture 股票 三丰软件 开发 中国文化 网文精选 阅读网 看图 日历 万年历 2018年10日历
2018-10-18 20:25:41
多播视频美女直播
↓电视,电影,美女直播,迅雷资源↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  编程开发知识库