0

I want to add some log in my service,so I using Annotation and AOP.At first,I write the code like this:

@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);
    } 
}

In my example,I have add @Transactional and add / by zero exception,but when do business job code still affect the database.It seems nothingt to do with the word @Transactional.How to change my code? I have try to change all my code in to a service,but still have not Transaction.

@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);
 } 
}

The common log service is :

@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;

}
flower
  • 2,212
  • 3
  • 29
  • 44
  • 1
    You are calling the transactional method from the same class. See this: https://stackoverflow.com/questions/43280460/spring-self-injection-for-transactions/43282215 – x4rf41 Mar 11 '19 at 15:39
  • from the same class?I only use `Transactional` one time – flower Mar 11 '19 at 15:50
  • 3
    `triggerSome` and `log` are in the same class, if `triggerSome` calls `log`, then `@Transactional` will be ignored. The reason is, that log is not called through the proxy – x4rf41 Mar 11 '19 at 15:55
  • I hava try to remove the method in a log service,but still have not Transaction. – flower Mar 12 '19 at 01:51

0 Answers0