@Autowired Spring 注释与 struts2 [英] @Autowired Spring annotation with struts2

查看:34
本文介绍了@Autowired Spring 注释与 struts2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Spring 的新手,我试图了解 @Autowired 注释如何与 struts2 操作一起工作.这是我的场景:

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.

我的问题是:如果我使用 @Autowired 注释,为什么我必须为 userBean 编写 bean id?它应该由 Spring Container 自动注入吗?

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?

如果我仍然需要在我的 applicationContext.xml 中编写两个 bean 定义,使用 @Autowired 注释有什么好处?

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

推荐答案

首先,UserBean 看起来是一个数据载体,不应该是 Spring 管理的 bean,除非你只有一个 User 对象您的申请.

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.

其次,content:component-scan 只会处理用 @Component 注释的类.由于您没有注释 UserBean 类,它不会被自动识别和 @Autowired 除非您将其明确声明为 bean,就像您在上下文文件中所做的那样.

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.

这篇关于@Autowired Spring 注释与 struts2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆