SpEL:在 bean 实例化期间获取当前 bean 名称 [英] SpEL: get current bean name during bean instantiation
问题描述
我正在尝试使用 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
编辑 2:
这在旧的基于 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
注释以摆脱所有 setter 时,似乎不支持具有 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屋!