Search code examples
javaspringconceptual

Spring injecting one property dynamically


I am new to Spring and i am stuck with a scenario where i need help. My Scenario is i have a bean definition for some specific module like this.

<bean name="ruleEngineAction" class="com.xxxxx.yyyy.UserAction" scope="prototype">
<property name="userManager">
    <ref bean="userManager" />
</property>
<property name="userDto">
        <ref bean="userDto" />
</property>
</bean>

now within this bean i want to use one more property but that depends on the application flow like

<property name="roleManager">
     <ref bean="roleManager">
</property>

so should i include this property with in the bean definition itself or i can do it dynamically in code because i don't want this property to be used a lot.

Please suggest me the right and efficient approach.


Solution

  • From what I understood from question, there is only one bean of type roleManager but the usage of roleManager is based on application flow.

    In this scenario, I would recommend you to inject roleManager to ruleEngineAction as you would do with any other bean but use the bean only when it is necessary.

    It is a bad practice to needless dependency to spring in normal classes like adding reference to applicationContext for fetching the bean dynamically at runtime.