2

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 are 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...

Muthu
  • 1,550
  • 10
  • 36
  • 62
  • 1
    Also, could you edit the question and add the full UserAction class and the complete context? – andyb Jul 02 '11 at 11:48

1 Answers1

2

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!

lepike
  • 726
  • 3
  • 11
  • Thanks lepike.... It works fine... My question is whats wrong in my code , when i use constructor injection... – Muthu Jul 03 '11 at 12:33
  • Sorry for misunderstood you. I gave you a workaround. I don't know what's the problem with your code. Constructor injection should have to work also. What is the bean definition of UserServiceTarget? Perhaps you should check the naming of the bean's id property. Hope you find the solution. – lepike Jul 07 '11 at 19:49