简体   繁体   中英

Dynamic dependency injection in spring configuration file

I need to know how to inject a dependency dynamically in spring configuration file. For an example I have a business logic class called 'Class A'. Inside that class, it handle a method called 'doSomething()'. According to the application this method can perform in two different ways(two type of implementations for same method). So I have declared a interface called 'Manager' with this method and create two implementation classes for same interface. Lets called them 'Impl1' and 'Impl2' which implement interface 'Manager'.

Interface Manager{
 void doSomething();
}

Class Impl1 implements Manager{ 

 public void doSomething(){
  //doIt like this way
 }

 Class Impl2 implements Manager{ 

 public void doSomething(){
  //doIt like that way
 }
}

Class A has a reference to 'Manager' interface called 'manager' which will be set at the deploy time via Spring DI. That injection can be either Impl1 object or Impl2 object. It will decide by the end user. So I have to offer two options to end user where he or she can decide which way he or she wants handle this 'doSomething()' method and according to his or her choice i'm going to inject relevant implementation class(Impl1 or Impl2).

Class A{ 

 private Manager manager; //this can be either Impl1 or Impl2

 public void setManager(Manager manager){
  this.manager = manager;
 }

 public void performLogic(){
  manager.doSomething();
 }
}

End user have only one chance to make that choice and after that application will use that implementation forever unless user wants to install a fresh copy of application again. How do i inject relevant implementation dynamically according to the user's choice in spring xml file.What is the best way to handle this situation? Ideas are welcome.

Thanks all in advance!

You need to use Spring profiles .

Use two profiles, wrap each implementation to one of them. Then at start time active one of profiles (using system properties for example).

What do you think something like below :

Class A{ 

 @Autowired 
 @Qualifier("Impl1")
 private Manager manager1; // Impl1

 @Autowired 
 @Qualifier("Impl1")
 private Manager manager2; // Impl2

 // getter setter for manager1 and manager2

 public void performLogic(){
  getUserChoiceManager().doSomething();
 }

 private Manager getUserChoiceManager() {
   // return manager according to user choice
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM