我是否需要实例变量的 setter 方法才能将值注入对象?
应用:包com.process;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[]args){
ApplicationContext context = new ClassPathXmlApplicationContext("SpringBeans.xml");
Person sh = (Person) context.getBean("Person");
sh.displayname();
}
}
人:
package com.process;
public class Person {
String name;
public void displayname(){
System.out.println(name);
}
}
<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-3.0.xsd">
<bean id="Person" class="com.process.Person">
<property name="name" value="Bob" />
</bean>
</beans>
当我运行应用程序时,它会失败并显示味精 -
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'name' of bean class [com.process.Person]: Bean property 'name' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
它仅适用于 setter 方法。
问题:
我需要为每个实例变量设置 setter 方法吗?