في بعض الأحيان يتم توصيل قواعد البيانات المتعددة في المشروع ، ويجب تكوين مصادر بيانات متعددة في الربيع. لقد واجهت هذه المشكلة مؤخرًا. نظرًا لأن مشروعي كان يعتمد على General DAO من قبل ، فهناك مشاكل ثابتة أثناء التكوين ، وهذه الطريقة تتعارض مع ملفات الموارد. إذا قمت بمسح ملف التعيين ، فيجب أن يكون اسم حبة SQLSessionFactory SQLSessionFactory. لا يمكن قراءة sqlsessionfactory2 أو أسماء أخرى. الحل النهائي هو كما يلي:
1. إضافة الفئة التالية multipledataSource.java إلى المشروع
حزمة com.etoak.util ؛ استيراد org.springframework.jdbc.datasource.lookup.abstractroutingdataSource ؛ الطبقة العامة multipledataSource يمتد AbstRactRoutingDataSource {private Static Final Threadlocal <string> dataSourceKey = new erranitablethreadlocal <string> () ؛ public static void setDataSourceKey (String dataSource) {datasourceKey.set (dataSource) ؛ } Override محمي كائن محدد CurrentLoftupKey () {// todo method method method tuto method dataSourceKey.get () ؛ }} ملف تكوين الربيع كما يلي:
<beans xmlns = "http://www.springframework.org/schema/beans" Xmlns: mvc = "http://www.springframework.org/schema/mvc" xmlns: xsi = "http://www.w3 XSI: Schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2 http://www.springframework.org/schema/mvc location = "classpath: db.properties"/> <bean id = "ds1" p: driverClassName = "$ {mysql.driver}" p: url = "$ {mysql.url}" p: username = "$ {mysql.username}" p: password = P: driverClassName = "$ {mysql2.driver}" p: url = "$ {mysql2.url}" p: username = "$ {mysql2.Username}" p: password = "$ {mysql2password}"/> <bean id = "multipletasource ref = "ds1"/> <property name = "TargetDatasources"> <map> <intrade key = "ds1" value-ref = "ds1"/> <interpt key = "dS2 P: mapperlocations = "classpath: com/etoak/dao/*-mapper.xml"/> <Elban> <bean> <property name = "basePackage" value = "com.etoak.dao"/> <property name = "markerInterface" value = "com.etoak.dao.basedao"/> فئة الاختبار كما يلي:
حزمة com.etoak.test ؛ استيراد org.springframework.context.applicationContext ؛ استيراد org.springframework.context.support.filesystemxmlapplicationContext ؛ استيراد com.etoak.dao.productdaoif ؛ استيراد com.etoak.util.multipledatasource ؛ اختبار الفئة العامة {public static void main (string [] args) {ApplicationContext ac = new FileSystemSmlapplicationContext ("WebContent/Web-INF/etoak-servlet.xml") ؛ ProductDaoif prodao = (ProductDaoif) ac.getBean (ProductDaoif.class) ؛ multipledataSource.setDatasourceKey ("DS1") ؛ int count1 = prodao.selectProductCount () ؛ multipledatasource.setDatasourceKey ("DS2") ؛ int count2 = prodao.selectProductCount () ؛ system.out.println (count1) ؛ system.out.println (count2) ؛ }}ما سبق هو كل محتوى هذه المقالة. آمل أن يكون ذلك مفيدًا لتعلم الجميع وآمل أن يدعم الجميع wulin.com أكثر.