set方式注入属性的一个小细节

来源:互联网 发布:与外国人学外语知乎 编辑:程序博客网 时间:2024/06/07 03:24

(1)正常情形

public class Student {    private int age;    public void setAge(int age) {        this.age = age;    }}
    <bean id="student" class="com.Student">        <property name="age" value="20"></property>    </bean>

(2)在配置bean的时候,property标签的name属性到底写什么呢?
不清楚具体情况的人,可能会有这样的错误认识:property标签的name属性与bean的属性名是对应的。大部分情况下,二者的确是对应的。但这并不意味着二者存在对应关系。看下面代码:

public class Student {    private int age;    public void setAge1(int age) {//改变了set方法名        this.age = age;    }}
    <bean id="student" class="com.Student">        <property name="age" value="20"></property>    </bean>

在这种情况下,属性注值失败,会抛出异常。因为:property标签的name属性与set方法对应。
(3)分析

    <bean id="student" class="com.Student">        <property name="age" value="20"></property>    </bean>

会调用setAge(arg)方法,并把value值传给方法的参数。
如果property标签的name属性是“age1”, 会调用setAge1(arg)方法。
如果property标签的name属性是“Abc”, 会调用setAbc(arg)方法。
如果property标签的name属性是“xxx”, 会调用setXxx(arg)方法。
(4)其实属性名是无关紧要的,set方法才是关键。Struts2中请求参数的注入也是set方式注入
(5)了解事物的真实情况还是很有必要的