spring 다 중 데이터 원본 설정 깊이 이해
위의 그림 에서 보 듯 이 모든 조각 은 묶 여 죽 는 것 을 지정 하고 여러 데이터 소스 라면 다음 그림 에서 만 그런 방식 일 수 있다.
Dao 층 코드 에 두 개의 Session Factory 가 죽 었 음 을 알 수 있 습 니 다.그러면 앞으로 데이터 원본 이 하나 더 있 으 면 코드 를 바 꾸 고 Session Factory 를 추가 해 야 합 니 다.이것 은 개폐 원칙 에 부합 되 지 않 습 니 다.
그렇다면 옳 은 방법 은
코드 는 다음 과 같 습 니 다:
1. applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.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.springframework.org/schema/context"
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://www.springframework.org/schema/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-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
http://www.springframework.org/schema/context 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/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/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.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd
http://www.springframework.org/schema/task 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">
<context:annotation-config />
<context:component-scan base-package="com"></context:component-scan>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:com/resource/config.properties</value>
</list>
</property>
</bean>
<bean id="dataSourceOne" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${dbOne.jdbc.driverClass}" />
<property name="jdbcUrl" value="${dbOne.jdbc.url}" />
<property name="user" value="${dbOne.jdbc.user}" />
<property name="password" value="${dbOne.jdbc.password}" />
<property name="initialPoolSize" value="${dbOne.jdbc.initialPoolSize}" />
<property name="minPoolSize" value="${dbOne.jdbc.minPoolSize}" />
<property name="maxPoolSize" value="${dbOne.jdbc.maxPoolSize}" />
</bean>
<bean id="dataSourceTwo" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${dbTwo.jdbc.driverClass}" />
<property name="jdbcUrl" value="${dbTwo.jdbc.url}" />
<property name="user" value="${dbTwo.jdbc.user}" />
<property name="password" value="${dbTwo.jdbc.password}" />
<property name="initialPoolSize" value="${dbTwo.jdbc.initialPoolSize}" />
<property name="minPoolSize" value="${dbTwo.jdbc.minPoolSize}" />
<property name="maxPoolSize" value="${dbTwo.jdbc.maxPoolSize}" />
</bean>
<bean id="dynamicDataSource" class="com.core.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry value-ref="dataSourceOne" key="dataSourceOne"></entry>
<entry value-ref="dataSourceTwo" key="dataSourceTwo"></entry>
</map>
</property>
<property name="defaultTargetDataSource" ref="dataSourceOne">
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dynamicDataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hbm2ddl.auto">create</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.po</value>
</list>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<aop:config>
<aop:pointcut id="transactionPointCut" expression="execution(* com.dao..*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointCut" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:aspect id="dataSourceAspect" ref="dataSourceInterceptor">
<aop:pointcut id="daoOne" expression="execution(* com.dao.one.*.*(..))" />
<aop:pointcut id="daoTwo" expression="execution(* com.dao.two.*.*(..))" />
<aop:before pointcut-ref="daoOne" method="setdataSourceOne" />
<aop:before pointcut-ref="daoTwo" method="setdataSourceTwo" />
</aop:aspect>
</aop:config>
</beans>
2. DynamicDataSource.class
package com.core;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource{
@Override
protected Object determineCurrentLookupKey() {
return DatabaseContextHolder.getCustomerType();
}
}
3. DatabaseContextHolder.class
package com.core;
public class 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. DataSourceInterceptor.class
package com.core;
import org.aspectj.lang.JoinPoint;
import org.springframework.stereotype.Component;
@Component
public class DataSourceInterceptor {
public void setdataSourceOne(JoinPoint jp) {
DatabaseContextHolder.setCustomerType("dataSourceOne");
}
public void setdataSourceTwo(JoinPoint jp) {
DatabaseContextHolder.setCustomerType("dataSourceTwo");
}
}
5.po 실체 클래스
package com.po;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "BTSF_BRAND", schema = "hotel")
public class Brand {
private String id;
private String names;
private String url;
@Id
@Column(name = "ID", unique = true, nullable = false, length = 10)
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
@Column(name = "NAMES", nullable = false, length = 50)
public String getNames() {
return this.names;
}
public void setNames(String names) {
this.names = names;
}
@Column(name = "URL", length = 200)
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
}
package com.po;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "CITY", schema = "car")
public class City {
private Integer id;
private String name;
@Id
@Column(name = "ID", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "NAMES", nullable = false, length = 50)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
6. BrandDaoImpl.class
package com.dao.one;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import com.po.Brand;
@Repository
public class BrandDaoImpl implements IBrandDao {
@Resource
protected SessionFactory sessionFactory;
@SuppressWarnings("unchecked")
@Override
public List<Brand> findAll() {
String hql = "from Brand";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return query.list();
}
}
7. CityDaoImpl.class
package com.dao.two;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import com.po.City;
@Repository
public class CityDaoImpl implements ICityDao {
@Resource
private SessionFactory sessionFactory;
@SuppressWarnings("unchecked")
@Override
public List<City> find() {
String hql = "from City";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return query.list();
}
}
8. DaoTest.class
package com.test;
import java.util.List;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import com.dao.one.IBrandDao;
import com.dao.two.ICityDao;
import com.po.Brand;
import com.po.City;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:com/resource/applicationContext.xml")
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
public class DaoTest {
@Resource
private IBrandDao brandDao;
@Resource
private ICityDao cityDao;
@Test
public void testList() {
List<Brand> brands = brandDao.findAll();
System.out.println(brands.size());
List<City> cities = cityDao.find();
System.out.println(cities.size());
}
}
op 을 이용 하여 데이터 원본 을 동적 으로 변경 하 는 목적 을 달성 합 니 다.데이터 원본 을 추가 하려 면 applicationContext 설정 파일 에 op 설정 을 추가 하고 DataSourceInterceptor 를 새로 만 들 면 됩 니 다.코드 를 변경 할 필요 가 없습니다.이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
thymeleaf로 HTML 페이지를 동적으로 만듭니다 (spring + gradle)지난번에는 에서 화면에 HTML을 표시했습니다. 이번에는 화면을 동적으로 움직여보고 싶기 때문에 입력한 문자를 화면에 표시시키고 싶습니다. 초보자의 비망록이므로 이상한 점 등 있으면 지적 받을 수 있으면 기쁩니다! ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.