找不到Spring xml上下文文件

时间:2013-12-11 10:09:31

标签: java spring

我正在尝试按照本教程学习Spring Framework:

http://www.tutorialspoint.com/spring/spring_hello_world_example.htm

我创建了一个新的Maven项目:

<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
     <version>3.2.5.RELEASE</version>
 </dependency>

不是Web应用程序。我想创建一个简单的java应用程序,我的主要方法是:

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();

如果我没错,ClassPathXmlApplicationContext构造函数会在src / main / resources文件夹中查找该文件。但是当我执行应用程序时,我得到了异常“File not found beans.xml”。我尝试使用beans.xml文件src / main / resources / beans.xml和大量路由的完整路径。

当我使用此代码检查我的文件是否存在时,它表示存在。

File f = new File("src/main/resources/beans.xml");
System.out.println("Exist test: " + f.exists());

我不明白。有什么帮助吗?

我想问的另一件事是我是否需要使用xml来获取依赖注入。我可以在不使用XML定义的情况下使用spring框架吗?

我见过像@Autowired这样的注释,但是我也无法让它工作。我想知道我是否需要使用xml +注释的组合。

2 个答案:

答案 0 :(得分:0)

如果您将文件放在类路径的根目录中(这就是您所做的),请使用

ApplicationContext context = new ClassPathXmlApplicationContext("/beans.xml");

引用它(开头的“/”)。

您不需要XML配置。看看Spring Framwork Reference Documentation。第5.9 Annotation-based container configuration章和5.12 Java-based container configuration详细解释了Java配置。

答案 1 :(得分:0)

ClassPathXmlApplicationContext不会在/ src / main / resources中查找该文件。它试图在类路径(jar文件的“根”)中找到它。

但是,当您构建应用程序时,您放在src / main / resources中的所有内容都将由maven放入“root”(在类路径中)。