プロジェクトで複数のデータベースが接続されている場合があり、複数のデータソースを春に構成する必要があります。私は最近この問題に遭遇しました。私のプロジェクトは以前に一般的なDAOに基づいていたため、構成中に一定の問題があり、この方法はリソースファイルと競合します。マッピングファイルをスキャンする場合、sqlSessionFactoryのBean名はsqlsessionFactoryでなければなりません。 sqlsessionfactory2または他の名前を読み取ることはできません。最終的な解決策は次のとおりです。
1.次のクラスMultipLedataSource.javaをプロジェクトに追加します
パッケージcom.etoak.util; Import org.springframework.jdbc.datasource.lookup.abstractroutingdatasource;パブリッククラス多重延長装置は、abstractroutingDataSourceを拡張します{private static final threadlocal <string> dataSourcekey = new EnersitableThreadLocal <String>(); public static void setDataSourcey(String DataSource){dataSourceKey.set(dataSource); } @Overrideプロテクションオブジェクトsequededcurrentlookupkey(){// todo auto-enerated method stub return datasourcekey.get(); }}スプリング構成ファイルは次のとおりです。
<beans xmlns = "http://www.springframework.org/schema/beans" xmlns:Context = "http://www.springframework.org/schema/context" xmlns:p = " XMLNS:MVC = "http://www.springframework.org/schema/mvc" xmlns:xsi = "http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd "> <コンテキスト:Component-scan Base-Package ="場所= "classpath:db.properties"/> <bean id = "ds1" p:driverclassname = "$ {mysql.driver}" p:url = "$ {mysql.url}" p:username = "$ {mysql.username}" id = "ds2" p:driverclassname = "$ {mysql2.driver}" p:url = "$ {mysql2.url}" p:username = "$ {mysql2.username}" p:password = "$ {mysql2.passord}" name = "DefaultTargetDataSource" ref = "ds1"/> <プロパティ名= "ターゲットダタソース"> <map> <entry key = "ds1"/> <entry key = "ds2" value-ref = "ds2"/>> </map> </propertion P:DataSource-Ref = "MultipledataSource" P:MapperLocations = "classpath:com/etoak/dao/*-mapper.xml"/> <bean> <bean> <プロパティ名= "basepackage" value = "com.etoak.dao"/> <プロパティ " </bean> </bean>テストクラスは次のとおりです。
パッケージcom.etoak.test; org.springframework.context.applicationcontextをインポートします。 import org.springframework.context.support.filesystemxmlapplicationcontext; com.etoak.dao.productdaoifをインポートします。 com.etoak.util.multipledatasourceをインポートします。 public class test {public static void main(string [] args){applicationContext AC = new FilesySystemXMLApplicationContext( "webcontent/web-inf/etoak-servlet.xml"); ProductDaoif prodao =(productdaoif)ac.getbean(croductdaoif.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をもっとサポートすることを願っています。