Autowire 2 instances of the same class in Spring

Viewed 699

I try to create 2 instances of the same class using Spring and I want to let Spring manage the Dependency Injection. The problem I encounter is the fact that any of these instances already have some @Autowired fields, same fields for both instances, so I cannot use @Configuration class (or I don't know how). For example, this is a sketch of my use case:

// what annotation to use here?
class A {
  @Autowired
  private SomeClass first;
  @Autowired
  private OtherClass second;

  private boolean aBool;
  // what annotation to use here? From where and how to call this constructor?
  public A(boolean aBool) {
    this.aBool = aBool;
  }
}

class B {
  @Autowired
  @Qualifier("aBoolTrue") // or a similar annotation
  private A oneInstanceOfA;  // oneInstanceOfA.aBool == true

  @Autowired
  @Qualifier("aBoolFalse")
  private A theOtherInstanceOfA;   // theOtherInstanceOfA.aBool == false
}

In this example, I need Spring to create and manage 2 distinct instances of the same class created through the same constructor (see the comments related to aBool), but with different parameter values. Is it possible to achieve this scenario using Spring?

1 Answers

Hello you could maybe just add a @Configuration class with 2 method

@Configuration
class ConfigurationClass{
  @Bean
  @Qualifier("aBoolTrue") // 
  public A oneInstanceOfA(SomeClass someClass, OtherClass second){ //Maybe With Other Qualifier for the parameter if needed  
     return new A(someClass, second, true);//Need another construtor
  }  

  @Bean
  @Qualifier("aBoolFalse")
  public A oneInstanceOfA(SomeClass someClass, OtherClass second){
     return new A(someClass, second, false);//Need another construtor
  }  
}
Related