How to dynamically inject a service using a runtime “qualifier” variable?

前端 未结 2 371
长发绾君心
长发绾君心 2020-12-13 04:23

I can\'t find a simple way to inject a component/service given a runtime value.

I started reading @ Spring\'s doc: http://docs.spring.io/spring/docs/current/spring-f

2条回答
  •  醉话见心
    2020-12-13 05:22

    According to this SO answer, using @Qualifier isn't going to help you much: Get bean from ApplicationContext by qualifier

    As for an alternative strategy:

    • if you are spring boot, you could use @ConditonalOnProperty or another Conditional.

    • a lookup service, as @aux suggests

    • just name your beans consistently and look them up by name at runtime.

    Note that your use case also appears to revolve around the scenario where beans are created on application startup, but the bean chosen needs to be resolved after the applicationContext has finished injecting the beans.

提交回复
热议问题