1. 程式人生 > >spring AOP中自身方法呼叫無法應用代理解決辦法

spring AOP中自身方法呼叫無法應用代理解決辦法

如下例:

public class MyServiceImpl implements MyService {
    public void do(){
        //the transaction annotation won't work if you directly invoke handle() method with 'this'
        this.handle();
    }

    @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
    public void
handle() { //sth with transaction } }

如果直接呼叫this的handle()方法則事務無法生效,原因是spring的AOP是通過代理實現的,像這樣直接呼叫本物件的方法是不會應用代理的。

可以使用如下兩種方式修改程式碼以應用事務:
(1)在MyServiceImpl中宣告一個MyService物件

public class MyServiceImpl implements MyService {
    @Autowired
    private MyService myService;

    public void do
(){ //use myService object myService.handle(); } @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) public void handle() { //sth. with transaction } }

(2)使用AopContext類

public class MyServiceImpl implements MyService {
    public void
do(){ //fetch current proxy objet from AopContext ((MyService)AopContext.currentProxy()).handle(); } @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) public void handle() { //sth with transaction } }

注意,原生的AspectJ是不會有這種自身呼叫的問題的,因為它不是基於代理的AOP框架。