Reputation: 99
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.
Upvotes: 0
Views: 455
Reputation: 388316
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.
Upvotes: 2
Reputation: 40318
There is no problem if you inject also.Whenever you access that class only it will create the object of that class.
Upvotes: 0
Reputation: 45060
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.
Upvotes: 1
Reputation: 16158
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
}
Upvotes: 0