I have multiple services and I want to autowire this services dynamically with using their class names. I have a method named "runCustomService" and this methods takes service's class names as input parameter (like "Service1" or "Service2"). I want to autowire these services and call its run method. Is there any way to do this?
@Service
public class Service1 extends BaseService{
@Autowired
private AnotherService anotherService;
public void run(){ .... }
}
@Service
public class Service2 extends BaseService{
@Autowired
private AnotherService anotherService;
public void run(){ .... }
}
public void runCustomService(String serviceClassName){
BaseService baseService = //Create baseService object from serviceClassName
baseService.run();
}
You could use qualifiers on your two services and get the correct bean based on the qualifier name from the ApplicationContext.
@Service
@Qualifier("Service1")
public class Service1 extends BaseService{
@Service
@Qualifier("Service2")
public class Service2 extends BaseService{
@Autowired
ApplicationContext applicationContext;
public void runCustomService(String serviceClassName){
BaseService baseService = applicationContext.getBean(serviceClassName);
baseService.run();
}
Get an instance of ApplicationContext and get bean by a class name:
@Autowired
ApplicationContext ctx;
Use the method getBean(...):
BaseService baseService = ctx.getBean(Service1.class.getName());
However, as the other answer says, I recommend you to use @Qualifier(...)
to inject a certain named conditionally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With