如何用Spring EL注入bean id?

时间:2017-09-21 12:05:59

标签: java xml spring spring-el

我想将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)?

1 个答案:

答案 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值。