我想将id
从XML配置传递给bean的构造函数。我不想实现BeanNameAware来执行此操作。我这样做的首选方法是Spring EL表达式:
<bean id="ws1" class="com.example.MyClass">
<constructor-arg name="id" value="#{#this.id}"/>
<!-- ... -->
</bean>
但是,#this
在这种情况下引用BeanExpressionContext
,不包含id
。
有没有办法使用Spring EL表达式访问id
(我的示例中为ws1
)?
答案 0 :(得分:2)
如果您需要知道目标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.
但是,对,你无法从SpEL访问它。 OTOH我不会在您的示例中发现大问题,无法将ws1
复制/粘贴到id
构造函数arg值。