복붙노트

[SPRING] Spring에 다중 트랜잭션 관리자가있는 다중 데이터 소스

SPRING

Spring에 다중 트랜잭션 관리자가있는 다중 데이터 소스

세 개의 DataSource (JDBC)가 Junit 응용 프로그램 컨텍스트 파일에 정의되어 있습니다. 그 중 두 가지는 트랜잭션으로 관리해야합니다. 이 두 데이터 소스를 사용할 때 어떤 메소드도 연결하지 않아도됩니다 (서로 완전히 독립적입니다).

비록 dataSource3가 활용되고 있지만 대응하는 메소드에서 관리되지는 않지만 dataSource2에 대해 하나의 트랜잭션 관리자를 사용할 때 나는 문제가 없었습니다. 그럼에도 불구하고 dataSource3만을 사용하는 다양한 DAO 클래스의 메소드를 관리해야 할 때 두 번째 트랜잭션 인 txManager2를 추가했습니다. 컨텍스트 파일에는 다음이 포함됩니다.

<context:component-scan base-package="my.pkg" />

<bean id="dataSource1"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="oracle.jdbc.OracleDriver" />
    <property name="url" value="jdbc:oracle:thin:@host1:1521:dbsid1" />
<property name="username" value="username1" />
<property name="password" value="password1" />
</bean>

<bean id="dataSource2"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="oracle.jdbc.OracleDriver" />
    <property name="url" value="jdbc:oracle:thin:@host2:1521:dbsid2" />
<property name="username" value="username2" />
<property name="password" value="password2" />
</bean>

<bean id="dataSource3"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="oracle.jdbc.OracleDriver" />
    <property name="url" value="jdbc:oracle:thin:@host3:1521:dbsid3" />
<property name="username" value="username3" />
<property name="password" value="password3" />
</bean>

<tx:annotation-driven/>

<bean id="txManager1" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <qualifier value="txManager1"/>
<property name="dataSource2" ref="dataSource2"/>
</bean>

<bean id="txManager2" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <qualifier value="txManager2"/>
<property name="dataSource3" ref="dataSource3"/>
</bean>

여러 트랜잭션 관리자가 정의되기 때문에, 나는 그들 자신의 가치로 자격을 부여 받았다. 보시다시피 dataSource3은 setter 메서드를 사용하여 주입됩니다.

package my.pkg;

@Component
public class MyDAO {

    private DataSource dataSource3;

    // Read only from datasource
    @Autowired
    @Qualifier("dataSource")
    public void setDataSource(DataSource ds) {
        template = new NamedParameterJdbcTemplate(ds);
    }

    // Performs reads/updates/inserts from datasource2
    @Autowired
    @Qualifier("dataSource2")
    public void setDataSource2(DataSource ds) {
        iTemplate = new NamedParameterJdbcTemplate(ds);
    }

    // Performs reads/updates/inserts from datasource3
    @Autowired
    @Qualifier("dataSource3")
    public void setDataSource3(DataSource ds) {
        dataSource3 = ds;
        uTemplate = new NamedParameterJdbcTemplate(ds);
    }

    @Transactional("txManager1")    
    public String insertProcs() { }

    @Transactional("txManager2")    
    public String updateProcs() { }
}

그러나 Junit 유닛 테스트를 실행하면 다음과 같이 표시됩니다.

java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:308)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'txManager2' defined in class path resource [test-context.xml]: 

Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'dataSource3' of bean class 

[org.springframework.jdbc.datasource.DataSourceTransactionManager]: Bean property 'dataSource3' is not writable or has an invalid setter method. Does the parameter 

type of the setter match the return type of the getter?
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1363)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1085)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:516)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
        at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:84)
        at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)
        at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:280)
        at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:304)
        ... 24 more
    Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'dataSource3' of bean class 

    [org.springframework.jdbc.datasource.DataSourceTransactionManager]: Bean property 'dataSource3' is not writable or has an invalid setter method. Does the parameter 

    type of the setter match the return type of the getter?
        at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1052)
        at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:921)
        at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:76)
        at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1360)

문제의 근원이 어디인지 아는가?

수락 된 응답에 따라 의도 한 기능을 수행하기 위해 다음과 같이 변경되었습니다.

<tx:annotation-driven transaction-manager="txManager1"/>

<bean id="txManager1" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <qualifier value="txManager1"/>
    <property name="dataSource" ref="dataSource2"/>
</bean>

<bean id="txManager2" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <qualifier value="txManager2"/>
    <property name="dataSource" ref="dataSource3"/>
</bean>

@Qualifier ( "dataSource")가 수정 되었어야합니다 (본인의 실수).

    // Read only from datasource
    @Autowired
    @Qualifier("dataSource1")
    public void setDataSource1(DataSource ds) {
        template = new NamedParameterJdbcTemplate(ds);
    }

해결법

  1. ==============================

    1.구성에 문제가 거의 없습니다.

    구성에 문제가 거의 없습니다.

    <property name="dataSource2" ref="dataSource2"/>
    <property name="dataSource3" ref="dataSource3"/>
    

    bean 이름은 다르지만 특성 이름은 다릅니다. 다음과 같이 변경해야합니다.

    <property name="dataSource" ref="dataSource2"/>
    <property name="dataSource" ref="dataSource3"/>
    

    예 : txManager1 및 txManager2 beans에 대한 setter 속성에서 각각.

    두 번째 : @Qualifier ( "dataSource2")와 @Qualifier ( "dataSource3")는 잘못되었는데, 이는 데이터 소스 빈이 아니라 TX 관리자 빈을 한정하기 때문입니다.

    대신 @Resource ( "dataSource2") 및 @Resource ( "dataSource3")를 사용하거나 데이터 소스 bean을 한정 할 수 있습니다.

    셋째 : @Qualifier ( "dataSource"). 한정자와 빈의 이름을 불평하지 않는다는 것을 주목하십시오 (주의 : dataSource1입니다)

    마지막으로 tx : annotation-driven을 정의했습니다. bean 이름이 transactionManager 인 트랜잭션 관리자를 기대합니다. 당신은 bean 정의도주지 못했기 때문에 실패 할 것이다.

  2. from https://stackoverflow.com/questions/23038261/multiple-datasources-with-multiple-transaction-managers-in-spring by cc-by-sa and MIT license