SpEL in @Qualifier refer to same bean

后端 未结 1 949
陌清茗
陌清茗 2021-01-22 02:14

I am interested to inject a bean reference, which is resolved based on another property on the same bean:

@Autowired
@Qualifier(\"#{\'prefix\' + actualQualifier}         


        
相关标签:
1条回答
  • 2021-01-22 03:07

    AFAIK, this will not work. SpEL has no access to variables of the enclosing class. And anyway, it looks like @Qualifier does not process SpEL expressions.

    I did some tests and never found how to use a SpEL expression as a @Qualifier value. This page from Spring forums (and the error messages from Spring) let me think that in fact @Qualifier only takes a String and does not try to evaluate a SpEL expression.

    My conclusion is that way will lead you in a dead end.

    As suggested in this other answer, I think you'd better use a selector bean and set otherBean in an init method :

    @Bean(initMethod="init")
    class MyBean {
    ...
        @Autowired
        private BeanSelector beanSelector;
        private OtherBean otherBean
        private String actualQualifier;
    
        public void init() {
            otherBean = beanSelector(actualQualifier);
        }
    ...
    }
    

    and put all intelligence about the choice of otherBean in beanSelector.

    0 讨论(0)
提交回复
热议问题