简体   繁体   中英

Dependency injection according to conditions

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 Implemantations:

@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 according to my path variable ("source") . If source = one, inject MyServiceOne or if source = two, inject MyServiceTwo.

Is this possible?

It sounds like you need both of these to be available and each method invocation on the controller can choose a different one. So wire up both implementations, with a qualifier to distinguish them. Use the path variable in the controller method and let it decide programmatically which service to call.

I don't think it's possible and reasonable.

A @RestController s is by nature a singleton. It gets configured at startup and remains the same for every request.

The expression /{source} is being evaluated during a request at runtime, when the controller has already been set up.

The options to consider:

  1. Inject both services and, in the method, decide which one to pick.
  2. Create two separate controllers for each service.
  3. Utilise the application context and extract beans from there.

正如使用限定符从ApplicationContext获取bean中所描述的那样,您可以为每个服务实现添加限定符,并在myControllerFunc添加类似的myControllerFunc

BeanFactoryAnnotationUtils.qualifiedBeanOfType(ctx.getBeanFactory(), MyServiceInterface.class, source)

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