-2
@Service
abstract class A {
  protected MyObj obj;
  protected A(MyObj obj) {
    this.obj = obj;
  }
  public abstract XYZ getTrade();
}

@Service
public class B extends A {
   B(MyObj obj) {
     super(obj);
   }

   public XYZ getTrade() {} 
}

@Service
public class C extends A {
   C(MyObj obj) {
     super(obj);
   }

   public XYZ getTrade() {} 
}

@Controller
public class MyController {

  @GemMapping("/test")
  public void test() {
    MyObj obj = new MyObj();
    if(condition 1) {
       //call getTrade() method of class B
    }
    if(condition 2) {
       //call getTrade() method of class C
    }
  }
}

MyObj is a user-defined POJO that is not managed bean. I have the above classes. now I have to call getTrade() method based on some condition in Controller. Could you please help/advise?

sachinj
  • 1
  • 2
  • your question is missing information. like which service you want to inject in your controller. your controller code. what is `MyObj`? like is it component or COnfiguration or Bean? please fix your question – Shoshi Apr 23 '20 at 07:47
  • Hi Shoshi. I have added details. thanks – sachinj Apr 23 '20 at 08:02

2 Answers2

0

this answer is based on the information provided by the question.

to inject beans you could do:

@Controller
public class MyController {
  private final B b;
  private final C c;

  public MyController (B b, C c) {
    this.b = b;
    this.c = c;
  }
  .........
}

in this case, beans must have to have one no-args constructor. so, In your case what you can do is have a no-args constructor in each service. then set your myObj by setter. that will do the trick.

Shoshi
  • 2,254
  • 1
  • 29
  • 43
  • 1
    Thanks, Shoshi for the reply. here B and C are just for example. I will have 100 classes like this which will extend class A. Here I am trying to achieve polymorphism. In the base class, I will have common method and then in subclasses, I will have specific methods. – sachinj Apr 23 '20 at 08:17
  • you will have 100 services? what you are really trying to do? – Shoshi Apr 23 '20 at 08:19
  • I have to parser 100 types of trades – sachinj Apr 23 '20 at 08:21
  • 1
    Then you can use just one service. and in the service you can use other classes or methods to parse your 100 trades. i think you don't need to create 100 service for that. – Shoshi Apr 23 '20 at 08:43
0

If you want to achieve polyformism on your sevices you need to add a Qualifier in your classes B and C. So the question now became how to inject a service dynamically on runtime, and this is answered here: How to dynamically inject a service using a runtime "qualifier" variable?

robertobatts
  • 965
  • 11
  • 22