Spring constructor injection shows null When accessing it on methods
I am developing a small application with Struts2 + Spring + hibernate...Spring beans are injected properly on server start-up .. I have stepped through the setters on start up and they are injecting properly. However, I run the post method and then the post method(execute() in struts2) and the values that were injected ar开发者_如何学运维e null. Why does this happen?
Bean injection is :
<bean id="userAction" class="com.example.user.action.UserAction">
<constructor-arg index="0">
<ref bean="UserServiceTarget"/>
</constructor-arg>
</bean>
My Struts2 constructor is :
public UserAction(IUserService userService)
{
this.userService=userService;
}
Struts2 method is :
public String execute() {
this.user=(User)userService.findById(this.id);
}
But inside execute method userService value is null... When i inject they are injected prperly..
Thank you...
I think constructor-args are not the way to ijecting beans to another. I give you an example:
applicationContext.xml:
<bean id="userAction" class="com.example.user.action.UserAction"/>
<bean id="userServiceTarget" class="com.example.user.UserServiceTarget">
UserAction.java:
@Autowired
private UserServiceTarget userService;
You can use other configurations also. For example:
<bean id="userAction" class="com.example.user.action.UserAction">
<property name="userService" ref="UserServiceTarget"/>
</bean>
By this way the Autowired annotation not needed, only a setter.
I don't like xml so much, so the best way is to using Stereotype annotations. You can use @Service annotation on your service class and you can forget to declare the bean in the appcontext, but you should add two lines this way:
<context:annotation-config />
<context:component-scan base-package="com.example"/>
Hope I helped!
精彩评论