@Autowired Spring annotation with struts2

2019-08-04 16:54发布

问题:

I'm newbie of Spring, I try to understand how @Autowired annotation works with a struts2 action. This is my scenario:

UserBean.java

public class UserBean {
     private String userName;
     private int userAge;
     private String userGender;
     private String userJob;
     private String[] userHobbies;

     /*Getters and Setters */
}

UserAction.java

@Component
public class UserAction extends ActionSupport implements ModelDriven<UserBean> {

     @Autowired
     private UserBean userBean;

     public String execute() {
         return SUCCESS;
     }

     public String addUser() {
         return SUCCESS;
     }

     public UserBean getModel() {
         return userBean;
     }

     public UserBean getUserBean() {
         return userBean;
     }

     public void setUserBean(UserBean userBean) {
         this.userBean = userBean;
     }
 }

applicationContext.xml

<context:annotation-config />
<context:component-scan base-package="com.gmail.amato.giorgio.*" />

<bean id="userAction" class="com.gmail.amato.giorgio.UserAction"></bean>
<bean id="userBean" class="com.gmail.amato.giorgio.UserBean"></bean>

Now my program is fine, and I don't have any error: I can see a form, fill that and see a result back to me.

My question is: If I using @Autowired annotation, why I have to write bean id for the userBean? It should be injecting automatically by the Spring Container?

What is the advantage using @Autowired annotation if I have still to write both bean definition in my applicationContext.xml?

回答1:

Firstly, UserBean appears to be a data carrier and shouldn't be a spring managed bean unless you have only one User object in your application.

Secondly, the content:component-scan would take care of only classes that are annotated with @Component. Since you didn't annotate UserBean class, it won't be automatically identified and @Autowired unless you declare it explicitly as a bean, just like the way you did in your context file.