简体   繁体   English

如何使用Spring EL注入bean id?

[英]How to inject the bean id with Spring EL?

I want to pass the id from the XML config to the constructor of the bean. 我想将id从XML配置传递给bean的构造函数。 I don't want to implement BeanNameAware to do this. 我不想实现BeanNameAware来做到这一点。 My preferred way to do so would be a Spring EL expression like this: 我这样做的首选方式是这样的Spring EL表达式:

<bean id="ws1" class="com.example.MyClass">
    <constructor-arg name="id" value="#{#this.id}"/>
    <!-- ... -->
</bean>

However, #this refers to BeanExpressionContext in this case, what doesen't contain the id . 但是,在这种情况下, #this引用BeanExpressionContext ,其中不包含id

Is there a way to access the id ( ws1 in my example) with a Spring EL expression? 有没有办法用Spring EL表达式访问id (在我的示例中为ws1 )?

If you need to know the bean id in the target MyClass instance, you should consider to implement BeanNameAware : 如果您需要了解目标MyClass实例中的bean id,则应考虑实现BeanNameAware

 * Interface to be implemented by beans that want to be aware of their
 * bean name in a bean factory. Note that it is not usually recommended
 * that an object depends on its bean name, as this represents a potentially
 * brittle dependence on external configuration, as well as a possibly
 * unnecessary dependence on a Spring API.

But right, you can't get access to it from SpEL. 但是没错,您无法从SpEL访问它。 OTOH I don't see big problem in your sample to copy/paste ws1 to that id constructor arg value. OTOH我看不到您的示例ws1复制/粘贴到该id构造函数arg值的大问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM