SpEL:在bean实例化期间获取当前的bean名称 [英] SpEL: get current bean name during bean instantiation

查看:212
本文介绍了SpEL:在bean实例化期间获取当前的bean名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用SpEL获取当前实例化的bean的名称,以允许使用 @PropertySource 提供的不同属性来创建同一类的多个bean.我希望有以下类似的东西:

I am attempting to use SpEL to get the name of the bean currently being instantiated to allow multiple beans of same class to be created with different properties supplied by @PropertySource. I am hoping for something like the following:

public class SampleBean {
    @Value("${#{CurrentBeanName}.val}")
    private String val
}

其他豆:

public class OtherBean {

    @Autowired
    @Qualifier(name="BeanA")
    SampleBean beanA;

    @Autowired
    @Qualifier(name="BeanB")
    SampleBean beanB;
}

属性文件:

BeanA.val=VALUE A
BeanB.val=VALUE B

如果我将 beanName = BeanA 添加到我的属性文件中,则可以使用它

If I add beanName=BeanA to my properties file, I am able to get this to work with

@Value("${${beanName}.val}")

#{BeanName} 的处理方法有什么想法?如果这不可能,那么就可以了,但是如果可行,它将比我当前的解决方案干净得多.

Any ideas on what to do for #{BeanName}? If this is impossible then so be it, but if it works it would be much cleaner than my current solution.

或者以任何方式将常量从xml bean定义传递给SpEL?例如:

Or any way to pass a constant from the xml bean definition to SpEL? example:

<bean id="BeanA" class="...">
    <property name="prefix" value="BeanA"/>
</bean>

java:

public class SampleBean {
    @Value("${#{prefix}.val}")
    private String val
}

任何种类的属性或任何有效的方法

Any sort of attribute or anything would work

在基于XML的旧配置中这很简单

This is trivial in old XML based config

spring.xml:

spring.xml:

<bean id="beanA" class="SampleBean">
    <property name="val" value="${BeanA.val}"/>
</bean>
<bean id="beanB" class="SampleBean">
    <property name="val" value="${BeanB.val}"/>
</bean>

SampleBean.java:

SampleBean.java:

public class SampleBean {

    private String val;

    public void setVal (String val) {
        this.val = val;
    }
}

但是,当切换到新的 @Value 注释以摆脱所有设置方法时,似乎不支持具有diff属性的非单例(即,无法动态过滤 @值有关创建bean的参数)

However when switching to the new @Value annotations to get rid of all the setters, it seems non-singletons with diff properties aren't supported (i.e. no way to dynamically filter @Value arguments on bean creation)

推荐答案

否;无法引用当前bean.

No; it is not possible to reference the current bean.

编辑

要在下面发表您的评论,请使用与Java配置等效的

To address your comment below, the Java Configuration equivalent of

<bean id="BeanA" class="com.my.Foo">
    <property name="prefix" value="BeanA"/>
</bean>

@Bean
public Foo BeanA() {
    Foo a = new Foo();
    a.setPrefix("BeanA");
}

尽管,按照惯例,您可能将其命名为 beanA .

although, by convention, you'd probably name it beanA.

这篇关于SpEL:在bean实例化期间获取当前的bean名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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