I am a Spring newbie. I found that sometime we need to construct an object using runtime data, but fixed value is used in constructor inject of Spring. I know I could create a setter method and change the value with it, but I don't think this an elegant solution. Could any one tell me how to do it?
<bean id="bank" class="UsBank">
<property name="moneyLeft" value="100"/> <!-- initial value -->
</bean>
<bean id="bet" class="UsDollars" scope="prototype">
<constructor-arg value="#{ bank.moneyLeft }"/>
</bean>
Let's say the bank bean is injected somewhere, so you have an access to it:
bank.setMoneyLeft( 100 )
Bet currentBet = appContext.getBean( "bet" )
If this argument can to be computed with an arbitrary expression:
<bean id="bet" class="UsDollars" scope="prototype">
<constructor-arg value="#{ T(java.lang.Math).random() * 100.0 }"/>
</bean>
If your use case allows to use system properties:
<bean id="bet" class="UsDollars" scope="prototype">
<constructor-arg value="#{ systemProperties['moneyLeft'] }"/>
</bean>
to get the bean:
System.setProperty( "moneyLeft", "5000" )
Bet currentBet = appContext.getBean( "bet" )
You can read read more about SpEL.
One thing to note about making a bet bean prototype => if it is injected into another bean, it (another bean) also needs to be a prototype, or there is some AOP magic that can be used, but it may not be all that important in your case.
If the above bean does not have to be a prototype (which would mean you would only need a single instance of this bean, but not at the application context creation time), you can remove scope="prototype" and add a lazy="true". That would tell Spring to only attempt to create this bean when it is first referenced.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With