I am writing a simple spring program with the following files.
BeanRef.xml
<?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-3.0.xsd">
<bean id="refbean" class="com.springstarter.RefBean">
<property name="anotherBean" >
<ref bean="anotherbean"/>
</property>
</bean>
</beans>
AnotherXml.xml
<?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-3.0.xsd">
<bean id="anotherbean" class="com.springstarter.AnotherBean">
<property name="message" value="Hello World!"/>
</bean>
</beans>
RefBean.java
public class RefBean
{
private AnotherBean anotherBean;
public AnotherBean getAnotherBean()
{
return anotherBean;
}
public void setAnotherBean( AnotherBean anotherBean )
{
this.anotherBean = anotherBean;
}
}
AnotherBean.java
public class AnotherBean
{
private String message;
public String getMessage()
{
return message;
}
public void setMessage( String message )
{
this.message = message;
}
}
Main Program
public class BeanRefApp
{
public static void main( String[] args )
{
@SuppressWarnings( "resource" )
ApplicationContext context = new ClassPathXmlApplicationContext("BeanRef.xml");
RefBean starter = ( RefBean ) context.getBean( "refbean" );
System.out.println(starter.getAnotherBean().getMessage());
}
}
Package structure:
As you can see in BeanRef.xml i'm trying to reference anotherbean declared in AnotherXml.xml.On run, it throws this exception,
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'anotherbean' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:698)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1175)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
I think some inclusion code need to be added to BeanRef.xml to reference AnotherXml.xml. Kindly help me out.