I took a bean class and inside this class I took an inner bean. I've configured them both in configuration file. But When I'm trying to run my Java application it is throwing me exception saying "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'?" why I'm not getting welcome to inner bean? what to do?
Property defined correctly in configuration file.
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 uses the JavaBeans naming convention.
With a field like
private DemoBean db;
and a declaration like
<property name="db">
Spring expects a setter named setDb
, not setDB
like you have in your code. Change it to setDb
and your main
method will correctly print
Welcome to inner bean