2016-01-22 101 views
0

我正在用以下文件編寫一個簡單的spring程序。在另一個xml文件中聲明的引用bean

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()); 
    } 
} 

包裝結構:

enter image description here

正如你可以看到BeanRef.xml我想要引用AnotherXml.xml.On運行anotherbean宣佈,它拋出這個例外,

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。請幫助我。

回答

1

在你BeanRef.xml,導入beans標籤內的其他XML,如:

<import resource="classpath:AnotherXml.xml"/><!-- Assuming AnotherXml.xml is in your classpath as well--> 
相關問題