[Spring] 스프링 트렌젝션 처리 - JDBC기반 관리자 등록, <tx:advice> 설정, <aop:adivisor> 설정,
트랜젝션
: 비즈니스로직을 수행할 경우 일정부분까지 수행한 후 오류가 발생 시 현재까지의 모든 수행 내용을 처음으로 되돌리는 기능 ( 오라클의 Rollback / commit 과 비슷)
=> 스프링 프레임워크 트랜젝션 처리를 컨테이너가 자동으로 처리하도록 설정 가능
- AOP 필요
- applicationContext.xml에 트랜적션 관리 tx 네임스페이스 필요
- XML기반의 AOP 설정만 사용할 수 있고 어노테이션은 사용 불가
- <aop:adviser> 엘리먼트를 사용해야함 ( 트랜젝션관리 기능의 어드바이스는 직접 구현하지 않고 스프링 컨테이너가 자동으로 생성하게 함)
- 어드바이스 메서드의 이름을 알 수 없어서 <aop:aspect>사용불가
사용방법
1. 트랜젝션 관리자 등록
: PlatformTransactionManager 인터페이스를 구현한 클래스로 commit(), rollback() 메서드를 가지고 있음
<bean>에 등록 필요
<!-- 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=""></property>
<property name="password" value=""></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>
<!-- JDBC기반으로 동작하기 때문에 DataSourceTransactionManager 이용 -->
<!-- name 속성은 변경 불가 -->
<!-- JPA 기반으로 동작하면 JPATransactionManager 이용 -->
<!-- Mybatis도 도 따로 -->
<bean>등록했더라도 아직 메서드 실행 불가( 메서드 정의만 되어있고 내용이 없음 )
=> 어드바이스 등록을 통해 <bean>에 등록된 DataSourceTransactionManager 트랜젝션을 커밋, 롤백을 한다. (환경설정)
* 어드바이스 : 비즈니스 메서드 실행 전이나 후에 동작하여 비즈니스 메서드와 무관하게 공통기능 제공 / 대표적으로 예외처리, 트랜젝션
2. 트랜젝션 어드바이스 설정
: 클래스를 만들 필요 없이 스프링 컨테이너가 자동 생성!
<!-- Transaction Configuration -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
- transation-manager에 DataSourceTransactionManager의 객체를 주입해서 트랜젝션 관리
- 어드바이스 이름이나 메서드를 알 수 없음
- <tx:attributes><tx:method></></> : 트랜젝션에 적용할 메서드 지정
<tx:method> 앨리먼트 속성
속성 | 의미 |
name | 트랜젝션이 적용될 메서드 이름 지정 |
read-only | 읽기 전용 여부 지정(기본값 false) -> true일 경우 트랜젝션 관리대상에서 제외 됨 |
no-rollback-for | 트랜젝션을 롤백하지 않을 예외 지정 |
rollback-for | 트랜젝션을 롤백할 예외 지정 |
*<tx:method name="get" read-only="true"> - get으로 시작하는 모든 메서드들은 읽기 전용으로만 처리
=> 트랜젝션 관리 대상에서 제외(트랜젝션은 데이터 수정/삭제/추가 시 필요한 것)
3. <aop:advisor> 설정
- 어드바이스 이름과 메서드를 모름으로 <aop:aspect> 사용불가
- <aop:advisor>엘리먼트를 통해 만들어놓은 어드바이스와 포인트컷을 연결
<!-- Transaction Advisor Configuration -->
<aop:config>
<aop:pointcut expression="execution(* com.hhw.biz..*Impl.*(..))" id="txPointcut"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
: after 형식으로 어드바이스가 수행 됨 (수행과정에서 오류가 발생하면 트랜잭션이 생기는 것이기 때문)
어드바이스에서 rollback() 혹은 commit() 메서드가 호출 됨
트랜젝션은 메서드 단위로 관리되므로 예외가 발생하면 메서드 전체가 롤백처리 됨!