如何修复“使用 class 路径资源中定义的名称创建 bean 时出错”?

How to fix ''Error creating bean with name defined in class path resource"?

我拿了一颗豆子class,在这个class里面我拿了一颗豆子。我已经在配置文件中配置了它们。但是,当我尝试 运行 我的 Java 应用程序时,它向我抛出异常,说 "Error creating bean with name 'id1' defined in class path resource [spconfig.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'db' of bean class [SampleBean]: Bean property 'db' is not writable or has an invalid setter method. Did you mean 'DB'?" 为什么我不欢迎使用 inner bean?怎么办?

属性 在配置文件中正确定义。

SampleBean.java

public class SampleBean {

    private DemoBean db;

    public void setDB(DemoBean db) {
        this.db=db;
    }

    public void show() {
        db.m1();
    }
}
DemoBean.java

public class DemoBean {

    public void m1() {
        System.out.println("Welcome to inner bean");
    }
}

spconfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
        "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

 <beans>
 <bean id="id1" class = "SampleBean">
 <property name="db">
 <bean class = "DemoBean"/>
 </property>
 </bean>
 </beans>

Client.java

import org.springframework.beans.factory.*;
import org.springframework.beans.factory.xml.*;
import org.springframework.core.io.*;
public class Client {
    public static void main(String[] args) {


    Resource res = new ClassPathResource("spconfig.xml");
    @SuppressWarnings("deprecation")
    BeanFactory factory = new XmlBeanFactory(res);
    Object o = factory.getBean("id1");
    SampleBean sb = (SampleBean)o;
    sb.show();
    }

}


Spring 使用 JavaBeans naming convention.

这样的字段
private DemoBean db;

和像

这样的声明
<property name="db">

Spring 需要一个名为 setDb 的 setter,而不是代码中的 setDB。将其更改为 setDb 并且您的 main 方法将正确打印

Welcome to inner bean