简体   繁体   中英

Spring xml context file not found

I'm trying to learn Spring Framework following this tutorial:

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

I have create a new Maven project with:

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

Is not a Web application. I want to create a simple java application and my main method is:

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

If i'm not wrong ClassPathXmlApplicationContext constructor looks for the file on the src/main/resources folder. But when i execute the application i got the exception "File not found beans.xml". I tried with the full route to the beans.xml file src/main/resources/beans.xml and tons of routes.

When i use this code to check the existence of my file it says that exists.

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

I don't get it. Any help please?

Another thing that i wanted to ask is if i need to use xml to get Dependency Injection. Can i work with spring framework without using XML definitions?

I have seen Annotations like @Autowired and more but i can't get it working also. I wonder if i need to use a combination of xml+annotations.

If you place the file in the root directory of your classpath (and that is what you do) use

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

to reference it ("/" at the beginning).

You don't need XML configuration. Have a look at the Spring Framwork Reference Documentation . Chapter 5.9 Annotation-based container configuration and 5.12 Java-based container configuration explain Java Configuration in Detail.

ClassPathXmlApplicationContext doesn't look for the file in the /src/main/resources. It tries to find it in the classpath (the "root" of your jar file).

But everything you put in the src/main/resources will be put in the "root" (in the classpath so) by maven when you build your application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM