티스토리 뷰

[JAVA]/Spring

[Spring] 트랜젝션 처리

춘햄 2021. 6. 21. 11:06

트랜젝션은 비즈니스 로직을 수행하는 경우, 일정 부분까지 수행한 후 오류가 발생할 시 현재까지의 모든 수행 내용을 처음으로 되돌릴 수 있도록 구현하는 것이다. 

오라큰의 RollBack/Commit 과 비슷한 개념이라고 보면 된다.


Spring에서 트랜젝션을 사용하려면 마찬가지로 네임스페이스를 설정해야한다.


다음으로 commit과 rollback 메서드가 정의되어 있는 트랜젝션 매니져 인터페이스를 bean 태그로 등록하고, property로 dataSource를 받아야 한다.

 

◎applicationContext.xml

	<!-- DataSource Configuration -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
		<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:XE"></property>
		<property name="username" value="choonham"></property>
		<property name="password" value="6725"></property>
	</bean>
	
	<!-- Spring JdbcTemplate Configuration  -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<!-- Transaction Registration -->
	<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>

이제, <tx:advice> 태그를 사용해서 트랜잭션 관리 어드바이스를 설정한다.

지금까지는 AOP 관련 설정에서 사용한 모든 어드바이스 클래스를 직접 구현했지만, 트랜잭션 관리 기능의 어드바이스는 직접 구현하지 않고, 스프링 컨테이너가 <tx:advice> 설정을 참조하여 자동으로 생성한다.

 

즉, 우리는 관련 어드바이스 객체에 클래스 이름이나 메서드를 확인할 수 없다는 의미이며, 이는 <aspect> 를 사용하여 AOP 설정을 할 수 없다는 것이다. tx어드바이스는 <advisor> 를 사용하여 포인트컷을 설정해야한다.

 

◎applicationContext.xml

<!-- Transaction Registration -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	<property name="dataSource" ref="dataSource"></property>
</bean>

<!-- Transaction Configuration -->
<tx:advice id="txAdvice" transaction-manager="txManager">
	<tx:attributes>
		<tx:method name="get*" read-only="true"/>
        <!-- get으로 시작하는 모든 메서드는 select기능을 수행하기 떄문에 read-only를 설정하여 트랜잭션에서 제외 -->
		<tx:method name="*"/>
        <!-- 따라서 그 외 모든 메서드에 트랜잭션 적용-->
	</tx:attributes>
</tx:advice>

<!-- Transaction Advisor Configuration -->
<aop:config>
	<aop:pointcut expression="execution(* com.freeflux.biz..*Impl.*(..))" id="txPointcut"/>
	<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>

이때, 위와 같이 <tx:attributes> 태그를 사용하여 트랜잭션을 적용할 메서드를 지정할 수 있다.

 

<tx:method>에서 사용할 수 있는 속성은 다음과 같다.

속성 의미
name 트랜잭션이 적용될 메서드의 이름 지정
read-only 읽기 전용 여부 지정
no-rollback-for 트랜잭션을 롤백하지 않을 예외 지정
rollback-for 트랜잭션을 롤백할 예외 지정

 

Comments