때로는 여러 데이터베이스가 프로젝트에 연결되어 있으며 스프링에 여러 데이터 소스를 구성해야합니다. 최근 에이 문제가 발생했습니다. 내 프로젝트는 이전의 일반 DAO를 기반으로했기 때문에 구성 중에 지속적인 문제가 있으며이 방법은 리소스 파일과 충돌합니다. 매핑 파일을 스캔하면 sqlsessionfactory의 Bean 이름이 sqlsessionfactory 여야합니다. sqlsessionfactory2 또는 다른 이름을 읽을 수 없습니다. 최종 솔루션은 다음과 같습니다.
1. 프로젝트에 다음 클래스 Multipledatasource.java를 추가하십시오
패키지 com.etoak.util; org.springframework.jdbc.datasource.lookup.abstractroutingdatasource; Public Class Multipledatasource는 AbstractroutingDatasource를 확장합니다. public static void setDatasourcekey (String DataSource) {dataSourcey.set (DataSource); } @override Protected Object goginedCurrentLookUpkey () {// TODO 자동 생성 메소드 스텁 DataSourcekey.get (); }} 스프링 구성 파일은 다음과 같습니다.
<beans xmlns = "http://www.springframework.org/schema/beans"xmlns : context = "http://www.springframework.org/schema/context"xmlns : p = "http://www.spramwork.org/s" xmlns : mvc = "http://www.springframework.org/schema/mvc"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance : schemalocation ="http://www.spram/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd "> <context : component-scan base-package ="com "/> <mvc : 컨텍스트 : context : context : context : classpath : db.properties"/> <Id = "ds1" P : DriveSclassName = "$ {mysql.driver}"p : url = "$ {mysql.url}"p : username = "$ {mysql.username}"p : password = "$ {mysql.password}"/> <bean id = "ds2"p : driver class} p : url = "$ {mysql2.url}"p : username = "$ {mysql2.username}"p : password = "$ {mysql2.password}"/> <bean id = "multipledatasource"> <property name = "defaulttargetdatasource"ref = <attorces < "> key = "ds1"value-ref = "ds1"/> <Entry key = "ds2"value-Ref = "ds2"/> </map> </property> </bean> <bean> <bean id = "sqlsessionfactory1"p : datasource-ref = "multipledatasource"p : mapperlocations = "compperaak/*-capper.de. <ean> <ean> <property name = "basepackage"value = "com.etoak.dao"/> <property name = "MarkerInterface"value = "com.etoak.dao.basedao"/> </bean> </beans> 테스트 클래스는 다음과 같습니다.
패키지 com.etoak.test; import org.springframework.context.applicationcontext; import org.springframework.context.support.filesystemxmlapplicationContext; import com.etoak.dao.productdaoif; import com.etoak.util.multipledatasource; public class test {public static void main (String [] args) {ApplicationContext ac = new FileSystemxMlApplicationContext ( "WebContent/Web-Inf/etoak-servlet.xml"); ProductDaoif prodao = (productDaoif) ac.getBean (productDaoif.class); multipledatasource.setdatasourceykey ( "ds1"); int count1 = prodao.selectProductCount (); multipledatasource.setdatasourceykey ( "ds2"); int count2 = prodao.selectProductCount (); System.out.println (count1); System.out.println (count2); }}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.