프로젝트에서 여러 데이터 소스, 특히 데이터 동기화 또는 타이밍 작업과 같은 프로젝트에서 문제가 종종 발생합니다. 여러 데이터 소스에서 가장 번거로운 것은 여러 데이터 소스를 구성하는 것이 아니라 유연하고 동적으로 데이터 소스를 전환하는 방법입니다. 예를 들어, Spring 및 Hibernate Framework 프로젝트에서 Spring 구성의 데이터 소스를 데이터베이스에 연결하기 위해 데이터 소스를 구성한 다음 SessionFactory에 바인딩 한 다음 DAO 계층 코드에서 SessionFactory를 지정하여 데이터베이스 작업을 수행합니다.
위 그림과 같이, 각 블록은 바인딩되어야합니다. 여러 데이터 소스 인 경우 아래 그림과 동일 할 수 있습니다.
DAO 계층 코드로 두 개의 세션 별이 작성되었음을 알 수 있습니다. 이런 식으로 향후 다른 데이터 소스가 있으면 코드를 변경하고 SessionFactory를 추가해야합니다. 분명히 이것은 개방 및 폐쇄의 원리를 준수하지 않습니다.
그러면 올바른 방법은해야합니다
코드는 다음과 같습니다.
1. ApplicationContext.xml
<? xml 버전 = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://ww.w.w3.org/2001/xmlschema-instance" xmlns : aop = "http://www.springframework.org/schema/aop"xmlns : cache = "http://www.springframework.org/schema/cache"xmlns : context = "http://www.springframwork.org/schema/SCEMA xmlns : jdbc = "http://www.springframework.org/schema/jdbc"xmlns : jee = "http://www.springframework.org/schema/jee"xmlns : jms = "http://wwww.spramframegramegramegrewwork.org. xmlns : lang = "http://www.springframework.org/schema/lang"xmlns : mvc = "http://www.springframework.org/schema/mvc"xmlns : oxm = "http://www.spramframwork.org/schema/spramwork.org/schema. xmlns : p = "http://www.springframework.org/schema/p"xmlns : task = "http://www.springframework.org/schema/task"xmlns : tx = "http://wwww.springframwork.org/schemema/tx" xmlns : util = "http://www.springframework.org/schema/util"xsi : schemalocation = "http://www.springframework.org/schema/beans http://ww.springframework.org/schema/spride-bean.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.spramework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/sppron-jdbc- 3 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd http://wwwwwfframegma/org http://www.springframework.org/schema/jms/spring-jms-3.1.xsd http://www.springframework.org/schema/jms-3.1.xsd http://www.springframework.org/schemema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd http://www.springframework.org/schema/mvc http://www.spramework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd http://www.springframework.org/schema/oxm/sprring-3 http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd http://www.spramework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/util http://www.spramework.org/schema/util/spring-util-3 /> <context : component-scan base-package = "com"> </context : component-scan> <bean> <bean> <bean name = "locations"> <list> <slist> <slest> <slat> </value> </list> </property> </bean> <bean> <bean> <bean> <dataSourceon "Destrous-method ="close "> <property"> value = "$ {dbone.jdbc.driverclass}" /> <property name = "jdbcurl"value = "$ {dbone.jdbc.url}" /> <property "value ="$ {dbone.jdbc.user} "/> 이름 = "InitialPoolsize"value = "$ {dbone.jdbc.initialpoolsize}" /> <속성 이름 = "minpoolsize"value = "$ {dbone.jdbc.minpoolsize}" /> <property name = "maxpoolsize"value = "$ {dbone.jdbc.mize. id = "dataSourcetwo"destroy-method = "close"> <property name = "driverclass"value = "$ {dbtwo.jdbc.driverclass}" /> <property name = "jdbcurl"value = "$ {dbtwo.jdbc.url}"/> /> <property name = "password"value = "$ {dbtwo.jdbc.password}" /> <property name = "initialpoolsize"value = "$ {dbtwo.jdbc.initialpoolsize}" /> <속성 이름 = "minpoolsize"value = "$ {dbtwo.jdbc.minpoolsize}. 이름 = "maxpoolsize"value = "$ {dbtwo.jdbc.maxpoolsize}"/> </bean> <bean id = "dynamicDatasource"> <property name = "targetdatasources"> <map key-type = "java.lang.string"> at value-ref = "dataSourceon" "> datasourceon"> value-Ref = "dataSourcetwo"key = "dataSourcetwo"> </enterd> </map> </property> <property name = "defaultTargetDatasource"ref = "dataSourceone"> </property> </bean> <bean id = "sessionCactory"> <property name = "rep ="rep = "property"/> <property "/>. 이름 = "HibernateProperties"> <props> <prop key = "hibernate.dialect"> org.hibernate.dialect.mysqldialect </prop> <prop key = "hibernate.current_session_sonce_context_context_class"> org.springframework.orm.orm.orm.orm.orm.orm.orm key = "hibernate.show_sql"> false </prop> <prop key = "hibernate.format_sql"> true key = "hbm2ddl.auto"> create </prop> </props> </property> <property name = "packagestoscan "> <sont> com. id = "transactionManager"> <속성 이름 = "sessionFactory"ref = "sessionFactory" /> < /bean> <aop : config> <aop : pointcut id = "transactionPointCut"expression = "execution (*com.dao ..*. < /aop : config> <tx : 조언 id = "txadvice"transaction-manager = "transactionManager"> <tx : attributes> <tx : method name = "add*"propagation = "필수" /> <tx : 메소드 이름 = "save*"save*"propagation ="required " /> <tx : method name ="propgagation = "propagation ="the method name = "tropagation ="method ": <tx :" 전파 = "필수" /> <tx : 메소드 이름 = "*"read-foll = "true" /> < /tx : attributes> < /tx : 조언> <aop : config> <aop : "dataSourceaspect"ref = "dataSourceintercept"> <aop : pointcut id = "daoone" "expression ="))))))))). <aop : pointcut id = "daotwo"expression = "execution (*com.dao.two.*.*(..))" /> <aop : pointcut-ref = "daoone"method = "setdatasourceone" /> <aop : pointcut-ref = "daotwo"setdatasourcetwo " />>> /a < /aop : < /aop : < /aop : < /aop : <aop : <aop : pointcut-ref ="daotwo " </aop : config> </beans> 2. DynamicDatasource.class
패키지 com.core; org.springframework.jdbc.datasource.lookup.abstractroutingdatasource; Public Class DynamicDatasource는 AbsTrAtroutingDatasource를 확장합니다. }}
3. DatabaseContexTholder.class
패키지 com.core; 공개 클래스 DatabaseContexTholder {private static final tridelocal <string> contextholder = new ThreadLocal <string> (); public static void setCustomerType (String CustomerType) {ContexTholder.set (customertype); } public static String getCustomerType () {return ContexTholder.get (); } public static void clearcustomertype () {contextholder.remove (); }} 4. DataSourceinterceptor.class
패키지 com.core; import org.aspectj.lang.joinpoint; org.springframework.stereotyp.component import; @Component Public Class DataSourceInterceptor {public void setDatasourceone (joinpoint jp) {databaseContexTholder.setCustomerType ( "DataSourceOne"); } public void setdatasourcetwo (joinpoint jp) {databasecontextholder.setCustomerType ( "dataSourcetwo"); }} 5. PO 엔티티 클래스
패키지 com.po; javax.persistence.column import; javax.persistence.entity import; javax.persistence.id import; javax.persistence.table import; @entity @table (name = "btsf_brand", schema = "hotel") 공개 클래스 브랜드 {private String id; 개인 문자열 이름; 개인 문자열 URL; @id @column (name = "id", 고유 = true, nullable = false, length = 10) public String getId () {return this.id; } public void setId (String id) {this.id = id; } @Column (이름 = "이름", nullable = false, length = 50) public String getNames () {return this.names; } public void setNames (문자열 이름) {this.names = 이름; } @column (이름 = "url", length = 200) public String geturl () {return this.url; } public void seturl (String URL) {this.url = url; }} 패키지 com.po; javax.persistence.column import; javax.persistence.entity import; javax.persistence.id import; javax.persistence.table import; @entity @table (name = "city", schema = "car") public class city {개인 정수 ID; 개인 문자열 이름; @id @column (이름 = "id", 고유 = true, nullable = false) public integer getid () {return id; } public void setId (정수 ID) {this.id = id; } @Column (이름 = "이름", nullable = false, length = 50) public String getName () {return name; } public void setName (문자열 이름) {this.name = 이름; }} 6. Branddaoimpl.class
패키지 com.dao.one; Java.util.list 가져 오기; import javax.annotation.resource; import org.hibernate.query; import org.hibernate.sessionfactory; org.springframework.stereotype.repository import; import com.po.brand; @repository public class branddaoimpl은 ibranddao {@resource protected sessionfactory sessionfactory; @suppresswarnings ( "선택 취소") @override public list <rand> findall () {String Hql = "Brand"; query query = sessionfactory.getCurrentSession (). Createquery (HQL); return query.list (); }} 7. CityDaoimpl.class
패키지 com.dao.two; Java.util.list 가져 오기; import javax.annotation.resource; import org.hibernate.query; import org.hibernate.sessionfactory; org.springframework.stereotype.repository import; com.po.city 가져 오기; @repository public class CityDaoimpl은 IcityDao {@Resource private sessionFactory sessionFactory; @suppresswarnings ( "선택 취소") @override public list <ity> find () {String Hql = "From City"; query query = sessionfactory.getCurrentSession (). Createquery (HQL); return query.list (); }} 8. daotest.class
패키지 com.test; Java.util.list 가져 오기; import javax.annotation.resource; import org.junit.test; import org.junit.runner.runwith; org.springframework.test.context.contextConfiguration import; org.springframework.test.context.junit4.springjunit4classrunner; org.springframework.test.context.transaction.transactionConfiguration import; import com.dao.one.ibranddao; import com.dao.two.icitydao; import com.po.brand; com.po.city 가져 오기; @RunWith (SpringJunit4classRunner.class) @ContextConfiguration (locations = "classPath : com/resource/applicationcontext.xml") @transactionConfiguration (transactionManager = "TransactionManager", defaultrollback = false) public class daotest {@resource private ibranddao; @Resource 개인 IcityDao CityDao; @test public void testList () {list <brand> brands = branddao.findall (); System.out.println (brands.size ()); List <ity> 도시 = CityDao.Find (); System.out.println (cities.size ()); }} AOP를 사용하여 데이터 소스를 동적으로 변경하는 목적을 달성하십시오. 데이터 소스를 추가 해야하는 경우 ApplicationContext 구성 파일에 AOP 구성을 추가하고 새 DataSourceInterceptor 만 만들면됩니다. 코드를 변경하지 않고.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.