@Autowired Spring annotation with struts2

I am new to Spring, I am trying to understand how annotation @Autowired

works with 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 see the form, fill it out and see the result back.

My question is, if I use annotation @Autowired

, why do I have to write a bean id for the userBean? Should it be auto-injected by the Spring container?

What is the advantage of using annotation @Autowired

if I still need to write a bean definition in mine applicationContext.xml

?

+1


source to share


1 answer


First, it UserBean

appears to be a bearer and doesn't need to be a spring bean unless you only have one User object in your application.



Second, it content:component-scan

will only take care of classes annotated with @Component

. Since you have not annotated the UserBean class, it will not be automatically identified and @Autowired

unless you explicitly declare it as a bean, just like in your context file.

+1


source







All Articles