2013-01-09 51 views
1

enter image description here弹簧无关注入:FileNotFound异常

我在学习弹簧依赖注入。我有两种类型的代码。一个人工作,一个人不工作......但是,他们都为制作教程的人工作。

评论的代码给了我下面显示的错误。当我使用的ApplicationContext

异常螺纹

@SuppressWarnings("deprecation") 
public static void main(String[] args) { 

    //ApplicationContext factory = new ClassPathXmlApplicationContext("Beans.xml"); 

    //The code below works 
    BeanFactory factory = new XmlBeanFactory(new FileSystemResource("Beans.xml")); 
    HelloWorld obj = (HelloWorld) factory.getBean("helloworld"); 

    obj.getMessage(); 
} 

的beans.xml

<?xml version="1.0"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xmlns:jdbc="http://www.springframework.org/schema/jdbc" 
     xsi:schemaLocation=" 
      http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd 
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd   
     "> 


    <bean id="helloworld" class="com.vulab.hellow.HelloWorld"> 
     <property name="message" value="Hello World" /> 
    </bean> 
</beans> 

错误消息 “主” org.springframework.beans.factory.BeanDefinitionStoreException:IOException异常从解析XML文档类路径资源[Beans.xml];嵌套的异常是java.io.FileNotFoundException:类路径资源[Beans.xml]因为它不存在而不能打开

+0

文件Beans.xml或文件beans.xml?检查案件? –

+0

它在IDE中也是一样。 @JeromeC。 – AppSensei

+1

你把你的Beans.xml文件放在哪里?它是否在一个源文件夹中(当你编译你的应用程序时它是否被复制到你的classes文件夹中)? – Claudio

回答

2

要使XmlBeanFactory正常工作,Beans.xml必须位于与调用类相同的目录中。

一个简单的方法是确保Beans.xml位于您的类路径中。你可以将它们复制到src\resources然后用:

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Beans.xml"); 
HelloWorld obj = (HelloWorld) applicationContext.getBean("helloworld"); 

ClassPathXmlApplicationContext是绝对的文件位置不需要指定更方便。

注意:从Spring 3.1开始XmlBeanFactorydeprecated,这意味着如果从3.0更改,应该使用这种替代方法。

+1

那有用!谢谢......只是好奇这两种代码有什么意义呢? – AppSensei

+0

它们是不同的读者,默认情况下'XmlBeanFactory'不从类路径读取。 – Reimeus

1

对于ClassPathXmlApplicationContext,应用程序上下文XML文件将需要在您的ClassPath中可用。

如果您使用的是标准Maven目录布局,则需要将Beans.xml文件放入src/main/resources

如果您从IDE运行(看起来您使用的是截图中的Eclipse,但未明确说明IDE),那么您需要进入Properties-> Java Build Path并将src/main/resources添加到构建路径。

祝你好运,希望这有助于!