Announcement Announcement Module
Collapse
No announcement yet.
reference bean id in bean constructor Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • reference bean id in bean constructor

    I often find myself doing something like this

    Code:
        <bean class="com.example.FooBar" id="FRESH">
            <constructor-arg name="name" value="FRESH" />
            <constructor-arg name="rank" value="2" />
        </bean>
    
        <bean class="com.example.FooBar" id="STALE">
            <constructor-arg name="name" value="STALE" />
            <constructor-arg name="rank" value="1" />
        </bean>
    I want the bean to have a name internally (mainly for logging) and I generally want it to be the same as the bean id. Having to type it twice is not only inconvenient but tends to result in cut-and-paste error (I create a new bean by copying an old one and forget to change it in both places).

    Is there a better way to do this? Maybe a way to reference the id in the constructor like

    Code:
        <bean class="com.example.FooBar" id="STALE">
            <constructor-arg name="name" value="${id}" />
            <constructor-arg name="rank" value="1" />
        </bean>
    Thanks,
    Dan

  • #2
    I think you can do much more using SpEL. Have a look at the link below
    http://static.springsource.org/sprin...ndef-xml-based

    Comment


    • #3
      SpEL seems really powerful but I can't see a way to do what I want.

      Comment


      • #4
        Implement the BeanNameAware interface and your object will have the name injected by the container.

        Comment

        Working...
        X