- 트랜잭션이 필요한 메소드마다 트랜잭션 처리 코드가 중복돼서 나타나는 비효율적 코드에 활용이 가능 하다.
- InvocationHandler 인터페이스를 구현 하여 트랜잭션 부가기능을 부가 해 주는 TransactionHandler 를 작성 한다.
public class TransactionHandler implements InvocationHandler {
private Object target;
private PlatformTransactionManager platformTransactionManager;
private String pattern;
public void setTarget(Object target) {
this.target = target;
}
public void setPlatformTransactionManager(PlatformTransactionManager platformTransactionManager) {
this.platformTransactionManager = platformTransactionManager;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().startsWith(pattern)) {
return invokeInTransaction(method, args);
} else {
return method.invoke(target, args);
}
}
private Object invokeInTransaction(Method method, Object[] args) throws Throwable {
TransactionStatus status = this.platformTransactionManager.getTransaction(new DefaultTransactionDefinition());
try {
Object ret = method.invoke(target, args);
this.platformTransactionManager.commit(status);
return ret;
} catch (InvocationTargetException e) {
this.platformTransactionManager.rollback(status);
throw e.getTargetException();
}
}
}