setter在Spring Framework中如何工作?

pan*_*iya 0 java setter spring spring-mvc getter-setter

我是Spring Framework的新手。实际上我正在做一个实验spring

看这个HelloWorld.java

public class HelloWorld {

    private String messageee;

    public void setMessage(String messageee){
        this.messageee=messageee;
    }

    public void show(){
        System.out.println("message: "+messageee);
    }
}
Run Code Online (Sandbox Code Playgroud)

你看这个节目,我已经被外界声明为一个变量private命名为messageee和下一个被参数化可变setter命名为messageee。您会看到两者具有相同的名称。

好的..现在看这个bean文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="helloWorld" class="com.springframework.HelloWorld">
        <property name="message" value="Hello.. This is Spring Framework example."></property>
    </bean>

</beans>
Run Code Online (Sandbox Code Playgroud)

在这里,您会看到内部bean标签。我已将属性名称声明为message。我不明白,当我输入名称messageee时会出现如下错误:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'helloWorld' defined in class path resource [beans.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'messageee' of bean class [com.springframework.HelloWorld]: Bean property 'messageee' is not writable or has an invalid setter method. Did you mean 'message'?
Run Code Online (Sandbox Code Playgroud)

但是当我给这个名字时message。它运行成功。但是我没有任何消息的方法或任何类似名称的变量。那么,setter实际上如何运作?请您详细说明一下?

帮助将不胜感激!

JB *_*zet 5

您正在将字段(或实例变量)与属性混淆。

属性是来自Java Beans规范的术语。fooBean 的属性是可以使用称为getFoo()(或isFoo()用于布尔值)的getter方法访问和/或使用称为setter的方法进行设置的数据setFoo()

这些方法在内部执行的操作,无论它们是否获取/设置变量,无论该变量还被命名为foo还是其他名称,都完全无关紧要。重要的是吸气剂/装填剂的名称。

因此,当您定义bean并告诉Spring设置名为message的属性时,Spring将寻找一个名为的方法setMessage()。它不在乎bean类的私有字段。