Handling multiple implementations of a single Spring bean / interface in a single class field

Like this question , but I have this situation. Suppose I have one interface AccountServiceand two implementations: DefaultAccountServiceImpland SpecializedAccountServiceImpl(classes, as in the previous question ). The implementation is in the same class, but has a different bean implementation for different methods. Say:

@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
        ...
    }
}
+4
source share
3 answers

Use @Qualifier("beanName")

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

@Autowired @Qualifier("service2")
private AccountService service2;
+6
source

I do not really understand the difference. You just need to create two different beans in this case, and then annotate them with @Qualifier.

, :

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

    @Autowired
    @Qualifier("DefaultAccountServiceImpl")
    private AccountService serviceDAS;

    @Autowired
    @Qualifier("SpecializedAccountServiceImpl")
    private AccountService serviceSAS;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    HttpEntity<?> registerAccount(@RequestBody AccountRegisterRequestBody input) {
        /* Use ServiceDAS Here */
        ...
    }

    @RequestMapping(value = "/register/specialized", method = RequestMethod.POST)
    HttpEntity<?> registerSpecializedAccount(@RequestBody AccountRegisterRequestBody input) {
        /* Use ServiceSAS Here */
        ...
    }
}

@Resource :

@Resource(name = "DefaultAccountServiceImpl")
private AccountService serviceDAS;

@Resource(name = "SpecializedAccountServiceImpl")
private AccountService serviceSAS;

, .

0

, 1 , @Qualifier , , , factory.

, factory , . , Service 1 "SERVICE1" factory, 1 .

0

Source: https://habr.com/ru/post/1629592/


All Articles