在一个类字段中处理一个Spring bean /接口的几个实现

Mor*_*isa 4 java spring spring-boot

与此问题类似,但我有这种情况.假设我有一个AccountService接口和两个实现:DefaultAccountServiceImplSpecializedAccountServiceImpl(类似上一个问题中的类).实现在一个类中,但对于不同的方法具有不同的bean实现.说:

@RestController
@RequestMapping("/account")
public class AccountManagerRestController {

    @Autowired
    private AccountService service;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    HttpEntity<?> registerAccount(@RequestBody AccountRegisterRequestBody input) {
        // here the `service` is DefaultAccountServiceImpl
        ...
    }


    @RequestMapping(value = "/register/specialized", method = RequestMethod.POST)
    HttpEntity<?> registerSpecializedAccount(@RequestBody AccountRegisterRequestBody input) {
        // here the `service` is SpecializedAccountServiceImpl
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 6

使用 @Qualifier("beanName")

@Autowired @Qualifier("service1")
private AccountService service1;

@Autowired @Qualifier("service2")
private AccountService service2;
Run Code Online (Sandbox Code Playgroud)