简体   繁体   English

将参数传递给Spring中构造函数中引用的Bean

[英]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. 我想将参数传递给从Spring Context.xml中的另一个bean引用的bean。 Is it even possible ? 可能吗?

NOTE : The DISCARD bean would have different values when referenced from different beans. 注意:当从其他bean引用时,DISCARD bean将具有不同的值。

<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 : 有没有一种方法,我们可以使用Spring Expression Language使用bean来引用bean,从而可以实现以下目的:

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

Basically you've to make that bean a prototype bean, if it has different properties for different injection. 基本上,如果不同注入的属性不同,则必须将该bean制成原型bean。 And then, set the value for "CAUSE" key in a @PostConstruct method, of TimestampRangeMatcherModifier bean. 然后,在@PostConstruct方法的TimestampRangeMatcherModifier bean中设置"CAUSE"键的值。 In XML, you define such method using init-method attribute of bean tag. 在XML中,您可以使用bean标签的init-method属性定义这种方法。

Another approach would be by declaring the bean in-place, like this: 另一种方法是通过就地声明Bean,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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