This repository has been archived by the owner on Apr 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[ch05] UserServiceTx using dynamic proxy.
- Loading branch information
Showing
2 changed files
with
82 additions
and
0 deletions.
There are no files selected for viewing
52 changes: 52 additions & 0 deletions
52
src/main/java/ch01/springbook/user/TransactionHandler.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
package ch01.springbook.user; | ||
|
||
import java.lang.reflect.InvocationHandler; | ||
import java.lang.reflect.InvocationTargetException; | ||
import java.lang.reflect.Method; | ||
|
||
import org.springframework.transaction.PlatformTransactionManager; | ||
import org.springframework.transaction.TransactionStatus; | ||
import org.springframework.transaction.support.DefaultTransactionDefinition; | ||
|
||
public class TransactionHandler implements InvocationHandler { | ||
|
||
private Object target; | ||
private PlatformTransactionManager transactionManager; | ||
private String pattern; | ||
|
||
public void setTarget(Object target) { | ||
this.target = target; | ||
} | ||
|
||
public void setTransactionManager(PlatformTransactionManager transactionManager) { | ||
this.transactionManager = transactionManager; | ||
} | ||
|
||
public void setPattern(String pattern) { | ||
this.pattern = pattern; | ||
} | ||
|
||
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 = transactionManager.getTransaction(new DefaultTransactionDefinition()); | ||
|
||
try { | ||
Object ret = method.invoke(target, args); | ||
transactionManager.commit(status); | ||
return ret; | ||
|
||
} catch (InvocationTargetException e) { | ||
transactionManager.rollback(status); | ||
throw e.getTargetException(); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters