1

I am using aspect to do few updates in elastic search after an entity is modified and persisted to db. I have methods to update one entity and a method to support bulk updating multiple entities? Internally, List method iterates over the method which persists the single object. How do I make the aspect to run only at list level?

Sample code below

@UpdateElastic
@Service
public Object saveOneObject(EntityObj obj){
   var savedObj = saveObj(obj); // method to persist entityObject
   return savedObj; // this object would now be passed to UpdateElastic aspect which 
                    // would perform some operation to cache this object in elastic search. 
}

@UpdateElasticList
@Service
public Object saveMultipleObjects(List<EntityObj> objs){

   List< EntityObj> savedObjects = new ArrayList<>();
   for (EntityObj obj: objs){
       var savedObj = saveOneObj(obj); // how do I avoid aspect to be called here but             // still call it if the saveOneObj is called from outside this file.
       savedObjects.add(savedObj); 
   }
    // method to persist entityObject
   return savedObjects; // this list of objects would now be passed to UpdateElasticList aspect which would perform some operation to cache this object in elastic search. 
}

  • Not clear on the requirement here. Is it like , the `saveOneObj()` method should not get advised when called from one class and get advised when called from another ? Are you using Spring AOP or AspectJ ? The current code shows internal method call to `saveOneObj()` which would never get advised in Spring AOP . – R.G Jun 27 '21 at 14:43
  • @R.G yes, it should not get advised from one class and should get advised from other class. I am using spring-aop . – Mayank Nema Jun 27 '21 at 14:46
  • 2
    Spring AOP does not provide that level of control ( to know the caller ) . It might be possible but not recommended ( [refer](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop-api-pointcuts-cflow)). Your requirement could be possible through AspectJ . You can identify the caller from examining the call stack etc , but I think it will be ugly – R.G Jun 27 '21 at 15:37
  • @R.G Thanks for the documentation link. Agree that it might be ugly and might be hard to control if a new file/class is introduced. I think what would be best in this case would be to make saveOneObj protected and always handle at list method. – Mayank Nema Jun 27 '21 at 18:13
  • 1
    @MayankNema, in my answer to the question this one is marked as a duplicate of you find a link to sample code (Spring-internal tests) concerning `ControlFlowPointcut`. It also explains how you could solve the problem in native AspectJ, which also works nicely as a Spring AOP replacement if configured correctly. – kriegaex Jun 28 '21 at 02:02

0 Answers0