hellzone
hellzone

Reputation: 5236

How to autowire Spring service with Class name?

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();
}

Upvotes: 4

Views: 5823

Answers (2)

Plog
Plog

Reputation: 9622

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();
}

Upvotes: 6

Nikolas
Nikolas

Reputation: 44398

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.

Upvotes: 4

Related Questions