我正在编写一个包含以下文件的简单弹簧程序。
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;
}
}
主程序
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());
}
}
包结构:
正如您在BeanRef.xml中看到的那样,我试图引用AnotherXml.xml.On中声明的另一个bean,它会抛出此异常,
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)
我认为需要将一些包含代码添加到BeanRef.xml以引用AnotherXml.xml。请帮助我。
答案 0 :(得分:1)
在BeanRef.xml
中,导入beans
标记中的其他xml,如:
<import resource="classpath:AnotherXml.xml"/><!-- Assuming AnotherXml.xml is in your classpath as well-->
答案 1 :(得分:1)
请你试试这个
<import resource="classpath:config/spring/that-other-xml-conf.xml"/>
<bean id="yourCoolBean" class="org.jdong.MyCoolBean">
<property name="anotherBean" ref="thatOtherBean"/>
</bean>
请找到相同的参考链接: how to reference a bean of another xml file in spring