0

I want to make sure, that in my controller classes all entities that I got from service are detached. To make it happen I thought about creating pointcut with Spring AOP that would point to every service method call if called by controller (or every service call called by not-service). The only problem is that I'm new to AOP, and I have no idea how to make it work, and I can't find anything useful on the Internet.

To make clear what I want to achieve here are some pseudo-classes:

@Controller
public class RestController(){

  private final MyService1 service1;
  private final MyService2 service2;


  public void restMethod1 {
    return service1.method1_1();
  }

  public void restMethod2(){
    service1.method1_1();

    return service1.method1_2();
  }
  
  public void restMethod3(){
    return service1.method2_1();
  }

}

@Service
public class MyService1 {

  public void method1_1() {
    return;
  }

  public void method1_2() {
    method1_1();
    return;
  }

}

@Service
public class MyService2 {

  private final MyService1 service1;

  public void method2_1() {
    return service1.method1_2();
  }

}

So my goal is to run aspect on

  • restMethod1() - once - because it calls a service once
  • restMethod2() - twice - because it calls a service twice
  • restMethod3() - once - because it calls a service once

My logic to this is to make a point cut that is

  • around method in @Service class if method is called from @Controller class or
  • around method in @Service class if method is called from class that is has no @Service annotation

I hope that it is possible, because we already found two bugs in our project related to getting not detached entities in controller. Or if there is a better solution, without AOP, I'll be happy to hear about it, but here are some things to consider:

  • @Transactional(NEVER) on @Controller does not do the trick :(
  • returning detached entities from service is not an option, because services call each other, and some of them expect attached entities
  • returning DTOs from services is not an option because of the above + the project is too big for such refactors right now
  • detaching entities in controller after every service method call is not an option, because reason above, and it would mean, that if other team takes this code, it will look confusing. Also, you can always forget about this, and there will be one random buggy method call
Vivent
  • 35
  • 2
  • 6
  • after more digging I found this: https://stackoverflow.com/questions/33909874/do-some-action-after-a-method-call-inside-another-method, but it looks rather complicated, and maybe someone has a better solution – Vivent Dec 02 '22 at 14:30
  • Sorry, despite your example and long explanation I do not understand what you want to achieve or which problem you are trying to solve. – kriegaex Dec 11 '22 at 06:21

0 Answers0