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

时间:2019-03-11 15:10:24

标签: spring spring-boot aop spring-aop

我想在服务中添加一些日志,所以我使用了Annotation和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(); //do business job and affect the database
        int i=1/0; //test Transactional
        logService.insertLog(pageId,(LogVo)obj);    
        return obj;
    }

    @Around("@annotation(com.mycompany.annotation.LogAnnotation)")
    public Object triggerSome(ProceedingJoinPoint pjp) throws Throwable { 
        return log( pjp);
    } 
}

在我的示例中,我添加了@Transactional和添加了/ by zero异常,但是业务作业代码仍然会影响数据库。这似乎与@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 个答案:

没有答案