我正试图按照本教程学习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+注释的组合。
ClassPathXmlApplicationContext不在/src/main/resources中查找文件。它试图在类路径(jar文件的"根")中找到它。
但是,当您构建应用程序时,maven会将您放在src/main/resources中的所有内容放在"根"(类路径中)中。
如果您将文件放在类路径的根目录中(这就是您所做的),请使用
ApplicationContext context = new ClassPathXmlApplicationContext("/beans.xml");
引用它(开头的"/")。
您不需要XML配置。请查看Spring框架参考文档。第5.9章基于注解的容器配置和5.12基于Java的容器配置详细解释了Java配置。