TODAY 0
Transactional 사용하기

XML 기반 선언적 트랜잭션 설정법에 더해서 어노테이션 기반의 방법을 사용할 수 있다. 트랜잭션을 자바 소스코드에 직접 선언하면 트랜잭션 선언과 트랜잭션이 적용되는 코드가 훨씬 가깝게 된다. 트랜잭션이 적용되는 코드는 거의 항상 그런 방식으로 배포되기 때문에 지나친 결합에 의한 위험성은 크지 않다.

@Transactional 어노테이션은 사용하기 쉽다.
// the service class that we want to make transactional
@Transactional
public class DefaultFooService implements FooService {
    Foo getFoo(String fooName);
    Foo getFoo(String fooName, String barName);
    void insertFoo(Foo foo);
    void updateFoo(Foo foo);
}

위 POJO 가 스프링 IoC 컨테이너에 빈으로 정의되었다면 이 빈 인스턴스는 XML 설정을 한 줄 추가하는 것으로 트랜잭션 처리 대상이 된다.

<!-- from the file 'context.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:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
 
    <!-- this is the service object that we want to make transactional -->
    <bean id="fooService" class="x.y.service.DefaultFooService"/>
 
    <!-- enable the configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="txManager"/>  
    <!- a PlatformTransactionManager is still required -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- (this dependency is defined somewhere else) -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- other <bean/> definitions here -->
</beans>

<tx:annotation-driven/> 태그의 transaction-manager 속성도 PlatformTransactionManager 빈의 이름이transactionManager 인 경우에 생략될 수 있다.
자바 기반 설정을 사용한다면 @EnableTransactionManagement 어노테이션을 사용해서 동일한 효과를 얻을 수 있다. 간단히 이 어노테이션을 @Configuration 클래스에 추가하면 된다.

메서드 가시성과 @Transactional

메서드 가시성과 @Transactional
프록시를 사용할 때, @Transactional 어노테이션은 반드시 public 메서드에 적용되어야 한다. protected, private, package-visible 메서드에 @Transactional 어노테이션이 추가되면 에러가 발생하지는 않지만 해당 메서드에 트랜잭션 설정이 적용되지 않는다. non-public 메서드에 어노테이션을 적용하고 싶다면 AspectJ사용을 고려하라.

< 결론 > 
@Transactional
어노테이션은 인터페이스 정의, 인터페이스의 메서드, 클래스 정의, 클래스의 public 메서드에 적용할 수 있다.
하지만 @Transactional 어노테이션을 추가하는 것 만으로 트랜잭션을 활성화 할 수는 없다.
@Transactional 어노테이션은 런타임 인프라가 @Transactional 을 인지하고 적절한 빈과 트랜잭션 동작을 설정하기 위해 사용되는 메타메이터가 된다.
 엘레멘트가 트랜잭션 동작의 스위치가 된다.

 

참고:http://bbans.blogspot.com/2014/06/transactional-spring.html#!/2014/06/transactional-spring.html
참고:http://wikibook.co.kr/article/transaction-management-using-spring/
참고:http://parkcheolu.tistory.com/35