@Qualifier中的SpEL引用相同的bean [英] SpEL in @Qualifier refer to same bean

查看:353
本文介绍了@Qualifier中的SpEL引用相同的bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有兴趣注入一个bean引用,该引用是基于同一个bean上的另一个属性来解析的:

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

@Autowired
@Qualifier("#{'prefix' + actualQualifier}")
private OtherBean otherBean

private String actualQualifier;

这将确保"actualQualifier"和"otherBean"之间的关系正确.

This would ensure that the relationship between "actualQualifier" and "otherBean" is correct.

有许多配置为OtherBean类型的bean.

There is a number of beans configured of the type OtherBean.

我可以确保在自动装配/注入开始之前为"actualQualifier"设置了一个值.

I can make sure that "actualQualifier" has a value set before autowiring/injection begins.

我无法找到任何方法来引用当前正在自动装配的同一bean上的另一个属性值(就JavaBean而言).

I am unable to find any way to reference another property value (in the JavaBean sense) on the same bean that is currently being autowired.

推荐答案

AFAIK,此方法无效. SpEL不能访问封闭类的变量.而且,看起来@Qualifier不能处理SpEL表达式.

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.

我做了一些测试,但从未发现如何将SpEL表达式用作@Qualifier值.

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.

如其他答案所述,我认为您最好使用选择器bean并在其中设置otherBean初始化方法:

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);
    }
...
}

,并将所有有关选择otherBean的情报都放在beanSelector中.

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

这篇关于@Qualifier中的SpEL引用相同的bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆