Pergunta

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.

Foi útil?

Solução

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.

Outras dicas

Whether or not, you inject this bean, it'll anyways be created by Spring. Why not just include the property in your UserAction and whether to use it or not, can be decided in your class. No harm in having the bean injected, because you'll anyways use it for some scenarios.

Had the scenario been like, the object won't be created, if you don't inject/use, then it would make sense to consider this situation, but since Spring will create the object anyways, it really shouldn't be a problem to just inject it.

Well you need to add new property with getter and setter in your class com.xxxxx.yyyy.UserAction for roleManager like :

class UserAction {
   // your previous properties userManager, userDto, etc.

   private RoleManager roleManager; // assuming interface/class as RoleManager for roleManager

   // getter and setter for roleManager

   // your other action methods which will use roleManager

}

There is no problem if you inject also.Whenever you access that class only it will create the object of that class.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top