简体   繁体   中英

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. I don't want to implement BeanNameAware to do this. My preferred way to do so would be a Spring EL expression like this:

<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 .

Is there a way to access the id ( ws1 in my example) with a Spring EL expression?

If you need to know the bean id in the target MyClass instance, you should consider to implement 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. OTOH I don't see big problem in your sample to copy/paste ws1 to that id constructor arg value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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