Java – Conditional Dependency Injection (Inject)

Conditional Dependency Injection (Inject)… here is a solution to the problem.

Conditional Dependency Injection (Inject)

My Controller:

@RestController
@RequestMapping("/mypath")
public class MyController {
   @Autowired
   MyServiceInterface service;

@PostMapping("/{source}")
   void myControllerFunc(@PathVariable String source, @RequestBody MyObject obj) {
       ...
       Object myServiceObj = service.myServiceFunc(param);
       ...
   }
}

My service interface:

public interface MyServiceInterface {

Object myServiceFunc(String param);

}

My service implementation:

@Service    
public class MyServiceOne {

Object myServiceFunc(String param) {
       ...
   }

}

@Service
public class MyServiceTwo {

void myServiceFunc(String param) {
       ...
   }

}

My spring-boot version: 1.5.7

I want to inject the service based on my path variable (“source”). If source = one, inject MyServiceOne, and if source = two, inject MyServiceTwo.

Is this possible?

Solution

It sounds like you need both to be available, and each method call on the Controller can choose a different method. So connect the two implementations and distinguish them with a qualifier. Use a path variable in the Controller method to programmatically decide which service to call.

Related Problems and Solutions