Muitas vezes encontramos problemas com várias fontes de dados em projetos, especialmente projetos como sincronização de dados ou tarefas de tempo. A coisa mais problemática sobre várias fontes de dados não é configurar várias fontes de dados, mas como alternar as fontes de dados de maneira flexível e dinâmica. Por exemplo, em um projeto Spring e Hibernate Framework, geralmente configuramos uma fonte de dados na configuração da primavera para conectar -se ao banco de dados e, em seguida, vinculá -lo às sessões e especificar o Factory no código da camada DAO para executar operações de banco de dados.
Conforme mostrado na figura acima, cada bloco deve estar ligado. Se for várias fontes de dados, só poderá ser o mesmo da figura abaixo.
Pode -se observar que duas sessões foram escritas no código da camada DAO. Dessa forma, se houver outra fonte de dados no futuro, você precisará alterar o código e adicionar uma sessão de session. Obviamente, isso não está em conformidade com o princípio de abrir e fechar.
Então a maneira correta de fazer isso deve ser
O código é o seguinte:
1. ApplicationContext.xml
<? xml versão = "1.0" coding = "utf-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http:/wwww.w3 xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: cache = "http://www.springframework.org/schema/cache" xmlns: context = "htttp.org/schema/cache" xmlns: context = "htttp.org/schema/cache" xmlns: "" xmlns: jdbc = "http://www.springframework.org/schema/jdbc" xmlns: jee = "http://www.springframework.org/schema/jee" xmlns: jms = "http://www.springframework.org/schema/jms" xmlns: lang = "http://www.springframework.org/schema/lang" xmlns: mvc = "http://www.springframework.org/schema/mvc" xmlns: oxm = "http://www.springframework.org/schema/oxm" xmlns: p = "" http.org/schema/oxm "xmlns: p =" xmlns:task="http://www.springframework.org/schema/task" 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-bans.xsd http://wwwwwwwwwwwwww.springwans/spring-bans.xsd http://wwwwwwwwwwwwwwwwans http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/cache http://www.springframework/schema/cache http://wwwwwwwwwwwwwwwww.org/schema/cache http://www.springframework.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/spring-jdbc-3.1.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd http://www.springframework.org/schema/jms/spring-jms-3.1.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframw.orgo.xchema http://wwwww.springframw.orgo.xchema/schema/ http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd http://www.springframework.org/schema/wwwwwwwwwwwwwwwwwwwwwwork.xwortwortwork/schema/wwwwwwwwwwwwwwwwwwwwwwwwwwork.xwwork.mask/wwwwwwwwwwwwwwwwwwwork.xwwork.mathwwwwwork http://www.springframework.org/schema/task/spring-task-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd "> contextation-config/> <context-scack-pack-pack-pack-packsd"> contextation-config/> <context-scack-pack-pack-packsd = <contextation-config/> <context-scack-pack-packsd = <Contexto> name = "Localizações"> <List> <Value> ClassPath: com/Resource/Config.properties </Value> </list> </Property> </bean> <bean id = "DataSourceOne" Destroy-Method = "Close"> <Nome da propriedade "Driver" = "$ {DBONE.JDBC.Rivercl) value = "$ {dbone.jdbc.url}" /> <names name = "user" value = "$ {dbone.jdbc.user}" /> <names name = "senha" value = "$ {dbone.jdbc.password} />neeNeNeNeNdenDin.tial {dbone.jdbc.password} />neeNeNeNd =" Initialnize " <propriedade name = "minpoolsize" value = "$ {dbone.jdbc.minpoolsize}" /> <propriedade name = "maxpoolsize" value = "$ {dbone.jdbc.maxpoolsize}" /> < /bean> <bening "(bergo) <brinAsT) value = "$ {dbtwo.jdbc.driverclass}" /> <propriedade name = "jdbcurl" value = "$ {dbtwo.jdbc.url}" /> <nome da propriedade = "user" value = "$ {dbtwo.jdbc.User}" /> <nome "" /> <propriedade name = "InitialPoolSize" value = "$ {dbtwo.jdbc.initialpoolsize}" /> <propriedade name = "minpoolsize" value = "$ {dbtwo.jdbc.Minpoolsize} /> <ww Name =" maxpoolsize " </bean> <bean id = "dynamicDataSource"> <propriedade name = "TargetDatasources"> <map key-type = "java.lang.string"> <Entrada-refs) </propriedade> <propriedade name = "defaultTargetDataSource" ref = "dataSourceOne"> </propriedade> </i bean> <bean id = "sessionfactory"> <propriedade name = "dataSource" ref = "dynamicdataSource"/> <nome da propriedade = "hibernateProperties"> <props> <pup " key = "hibernate.dialect"> org.hibernate.dialect.mysqldialect </prop> <props key = "hibernate.current_session_context_class"> org.springframework.orm.ibernate4.springsessionContext </prop> <pke = "hibernate.orm.shel.shel.shel.shel.shel.shel.Shel.Shel.Shel.Shel.Shel.Shel.Shel.Shel.Shel.Shel. key = "hibernate.format_sql"> true </prop> <props key = "hbm2ddl.auto"> criar </sp> </props> </property> <names name = "packagestoscan"> <list> <Value> com.po </valuory </list> </property> </bean> ref = "sessionFactory" /> </ Bean> <aOP: config> <aop: pointcut id = "transactionpointcut" expressão = "Execução (*com.dao ..*.*(..))" /> <aop: consultor advisor-ref = "txadvice "pcut-re =" t: "TOPTONCUTCUT" /"TXADVICE "p ("> transactCutcut " /" txadvice "p ("transactionpointcut" /" transação-manager = "transactionManager"> <tx: atributes> <tx: método name = "add*" propagation = "requerir" /> <tx: método name = "save*" propagação = "requerir" /> <tx: name "update*" propagação = "requerido" /> <tx: métod name = "delate* leitura somente = "true" /> < /tx: atributes> < /tx: conselhos> <aop: config> <aop: aspecto id = "datasourceaspect" ref = "dataSourceIntercept"> <aop: pointcut id = "daoone" expressão = "Execution (*com.dao.one.*.*. Expression = "Execução (*com.dao.two.*.*(..))" /> <AOP: antes de Pointcut-ref = "daoone" method = "setDataSourceOne" /> <aOP: antes de Pointcut-ref = "Daotwo" = "SetDataSourCetwo" /> < /aop: 2. DynamicDatasource.class
pacote com.core; importar org.springframework.jdbc.dataSource.lookup.abstractroutingDataSource; classe pública DynamicDataSource estende abstractrotingDataSource {@Override Protected Object determineCurrentLeoveKey () {return databaseContextholder.getCustomerType (); }} 3. DATABASECONTEXTHOLDER.CLASS
pacote com.core; classe pública DatabaseContextHolder {private Static final ThreadLocal <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. DataSourceIntercept.Class
pacote com.core; importar org.aspectj.lang.joinpoint; importar org.springframework.tereotype.component; @Component public class DataSourceInterceptor {public void SetDataSourceOne (JOUNPOINT JP) {DATABASECONTEXTHOLDER.SETCUSTOMERTYPE ("DataSourceOne"); } public void SetDataSourCetwo (JONCOPOINT JP) {DATABASECONTEXTHOLDER.SETCUSTOMERTYPE ("DataSourcetwo"); }} 5.
pacote com.po; importar javax.persistence.column; importar javax.persistence.Entity; importar javax.persistence.id; importar javax.persistence.table; @Entity @Table (name = "btsf_brand", schema = "hotel") marca de classe pública {private string id; nomes privados de string; URL privado de string; @Id @column (name = "id", exclusivo = true, nullable = false, length = 10) public string getId () {return this.id; } public void setId (string id) {this.id = id; } @Column (name = "nomes", nullable = false, comprimento = 50) public string getNames () {return this.names; } public void SetNames (nomes da string) {this.names = names; } @Column (name = "url", comprimento = 200) public string geturl () {return this.url; } public void Seturl (String url) {this.url = url; }} pacote com.po; importar javax.persistence.column; importar javax.persistence.Entity; importar javax.persistence.id; importar javax.persistence.table; @Entity @Table (Name = "City", Schema = "Car") Classe Public City {ID inteiro privado; nome de string privado; @Id @column (name = "id", exclusivo = true, nullable = false) public inteiro getId () {return id; } public void SetId (ID inteiro) {this.id = id; } @Column (name = "nomes", nullable = false, comprimento = 50) public string getName () {return name; } public void setName (nome da string) {this.name = name; }} 6. Branddaoimpl.class
pacote com.dao.one; importar java.util.list; importar javax.annotation.resource; importar org.hibernate.Query; importar org.Hibernate.SessionFactory; importar org.springframework.tereotype.repository; importação com.po.brand; @Repository Public Class BranddaoImpl implementa Ibranddao {@Resource Protected SessionFactory SessionFactory; @Suppresswarnings ("desmarcado") @Override Public List <Rand> findAll () {String hql = "da marca"; Query Query = sessionFactory.GetCurrentSession (). CreateEquery (HQL); retornar query.list (); }} 7. Citydaoimpl.class
pacote com.dao.two; importar java.util.list; importar javax.annotation.resource; importar org.hibernate.Query; importar org.Hibernate.SessionFactory; importar org.springframework.tereotype.repository; importação com.po.city; @Repository Public Class CityDaoImpl implementa icitydao {@Resource Private SessionFactory SessionFactory; @Suppresswarnings ("desmarcado") @Override Public List <City> find () {string hql = "da cidade"; Query Query = sessionFactory.GetCurrentSession (). CreateEquery (HQL); retornar query.list (); }} 8. Daotest.class
pacote com.test; importar java.util.list; importar javax.annotation.resource; importar org.junit.test; importar org.junit.runner.runwith; importar org.springframework.test.context.ContextConfiguration; importar org.springframework.test.context.junit4.springjunit4classrunner; importar org.springframework.test.context.transaction.transactionConfiguration; importação com.dao.one.ibranddao; importação com.dao.two.icitydao; importação com.po.brand; importação com.po.city; @Runwith (springjunit4classrunner.class) @ContextConfiguration (Locations = "ClassPath: com/Resource/ApplicationContext.xml") @TransactionConfiguration (transactionManager = "TransactionManager", Defaultring = False) Brand ClassoTest {@ResousDe @Resource Private Icitydao Citydao; @Test public void testlist () {list <rand> Brands = Branddao.findall (); System.out.println (BRANDS.SIZE ()); List <City> cidades = citydao.find (); System.out.println (cities.size ()); }} Use AOP para alcançar o objetivo de alterar dinamicamente a fonte de dados. Quando precisamos adicionar fontes de dados, precisamos adicionar apenas a configuração da AOP no arquivo de configuração ApplicationContext e criar um novo DataSourceInterceptor. Sem alterar nenhum código.
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.