Search code examples
javaspringjakarta-eeapplicationcontext

Passing a parameter to a bean referenced in a constructor in Spring


I want to pass a parameter to a bean referenced from another bean in Spring Context.xml. Is it even possible ?

NOTE : The DISCARD bean would have different values when referenced from different beans.

<bean id="dropBadTimestampFilter" class="TimestampRangeMatcherModifier">
    <constructor-arg index="0" value="_TIME"/>
    <constructor-arg index="1" ref="DISCARD" /> <!--Want to pass a prameter value to this-->
</bean>

<bean id="DISCARD" class="SettingModifier">
     <property name="fields">
         <map>
             <entry key="_ORG" value="CONSTANT"/>
             <entry key="CAUSE" value="______"/>  <!-- Want to be passed from bean referring it-->
         </map>
    </property>
</bean>

Is there a way that we could have a reference of bean using a bean using Spring Expression Language so that the following is possible :

<bean id="DISCARD" class="SettingModifier">
     <property name="fields">
         <map>
             <entry key="_ORG" value="CONSTANT"/>
             <entry key="CAUSE" value="#{dropBadTimestampFilter.CAUSE}"/>  <!-- Can this bean get reference of all the beans using it and not only dropBadTimestampFilter. -->
         </map>
    </property>
</bean>

Solution

  • Basically you've to make that bean a prototype bean, if it has different properties for different injection. And then, set the value for "CAUSE" key in a @PostConstruct method, of TimestampRangeMatcherModifier bean. In XML, you define such method using init-method attribute of bean tag.

    Another approach would be by declaring the bean in-place, like this:

    <bean id="dropBadTimestampFilter" class="TimestampRangeMatcherModifier">
        <constructor-arg index="0" value="_TIME"/>
        <constructor-arg index="1">
            <bean class="SettingModifier"> <!-- no need of id here -->
                <property name="fields">
                    <map>
                       <entry key="_ORG" value="CONSTANT"/>
                       <entry key="CAUSE" value="______"/>
                   </map>
                </property>
            </bean>
        </constructor-arg>
    </bean>