Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to autowire Spring service with Class name?

Tags:

java

spring

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();
}
like image 572
hellzone Avatar asked Dec 24 '22 13:12

hellzone


2 Answers

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();
}
like image 120
Plog Avatar answered Feb 03 '23 10:02

Plog


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.

like image 42
Nikolas Charalambidis Avatar answered Feb 03 '23 11:02

Nikolas Charalambidis