为什么Spring在Spring AOP中忽略了@Transactional注解?

8 浏览
0 Comments

为什么Spring在Spring AOP中忽略了@Transactional注解?

我想在我的服务中添加一些日志,所以我使用了注解和AOP。一开始,我写的代码是这样的:

@Aspect
@Component
public class LogAspect {
    @Autowired
    LogService logService;
    @Transactional
    Object log(ProceedingJoinPoint point) throws Throwable{ 
        Object obj = null; 
        Signature signature = point.getSignature();  
        MethodSignature methodSignature = (MethodSignature)signature;
        Method method = methodSignature.getMethod();
        LogAnnotation myAnno = method.getAnnotation(LogAnnotation.class); 
        String pageId=null;   
        JSONObject object=(JSONObject)point.getArgs()[0]; 
        pageId=object.getString("pageId"); 
        obj = point.proceed(); //进行业务处理并影响数据库
        int i=1/0; //测试事务
        logService.insertLog(pageId,(LogVo)obj);    
        return obj;
    }
    @Around("@annotation(com.mycompany.annotation.LogAnnotation)")
    public Object triggerSome(ProceedingJoinPoint pjp) throws Throwable { 
        return log( pjp);
    } 
}

在我的示例中,我添加了`@Transactional`注解并添加了一个除以零的异常,但是当执行业务处理代码时,仍然会影响数据库。似乎与`@Transactional`无关。如何改变我的代码?

我尝试将所有代码改为一个服务,但仍然没有事务。

@Aspect
@Component
public class LogAspect { 
   @Autowired
   LogService logService; 
   @Around("@annotation(com.mycompany.annotation.LogAnnotation)")
   public Object triggerSome(ProceedingJoinPoint pjp) throws Throwable { 
       return  logService.commonLog(pjp);
   } 
}

通用日志服务如下:

@Transactional(rollbackFor=Throwable.class)
@Override
public Object commonLog(ProceedingJoinPoint point) throws Throwable{ 
    Object obj = null; 
    Signature signature = point.getSignature();  
    MethodSignature methodSignature = (MethodSignature)signature;
    Method method = methodSignature.getMethod();
    LogAnnotation myAnno = method.getAnnotation(LogAnnotation.class);   
    String pageId=null;  
    JSONObject object=(JSONObject)point.getArgs()[0]; 
    pageId=object.getString("pageId"); 
    obj = point.proceed(); 
    int i=1/0; 
    LogService.insertLog(pageId,(LogVo)obj);     
    return obj;
}

0