Spring, java - different constructor args - best practice pattern

Viewed 77

Have the following structure in a spring rest mvc service app.

  • If controller A is called, 2 constructor arguments should be used to create Service B.
  • If controller B is called, 2 different constructor values should be used to create Service B.
  • Service A is injected into Controller A and Service B is injected in Service A.

Controller A -> Service A -> Service B (String param_url_1, RestTemplate param_template_1)

Controller B -> Service A -> Service B (String param_url_2, RestTemplate param_template_2)

Is there a recommended pattern to handle this?

Sample code:

@RequstMapping("v1/api")
public class ControllerA {

  ServiceA serviceA;

  ControlllerA(ServiceA serviceA){
     this.serviceA = serviceA
  }

  @GetMapping("/doSomething")
  public void doSomething{
    serviceA.doSomething();
  }
}

@RequstMapping("v2/api")
public class ControllerB {

   ServiceA serviceA;

   ControlllerB(ServiceA serviceA){
     this.serviceA = serviceA
   }

   @GetMapping("/doSomethingDifferent")
   public void doSomething{
     serviceA.doSomething();
   }
}


public class ServiceA {

   ServiceB serviceB;

   ServiceA(ServiceB serviceB){
     this.serviceB = serviceB
   }

   public void doSomething{{
    serviceB.serviceBMethod();
   }
}

public class ServiceB {

  ServiceB(String url,
         RestTemplate template){
     this.url = url;
     this.template = template;
   }

   public void serviceBMethod{{
    template.invoke(url);
   }
 }

In the above example url and template would have different values depending on which controller started the invocation.

1 Answers
Related