I am creating an application which uses Spring beans and I need to initialize ApplicationContext
from xml
. As it is not a server application, it doesn't have WEB-INF
folder.So, where I should put the xml
file?

- 6,661
- 7
- 48
- 63

- 3,439
- 12
- 51
- 75
3 Answers
The spring documentation for this topic is a little overwhelming at first. A handy starting point in the spring documentation for application context config is here
A file system xml application context is probably the easiest to start with. So:
ApplicationContext appCtx =
new FileSystemXmlApplicationContext("/path/to/springconfig.xml");
Use ClassPathApplicationContext
if you have the xml configuration in your application class path. In this example it might be a springconfig.xml under a project directory src/config/springconfig.xml.
ApplicationContext appCtx =
new ClassPathXmlApplicationContext("config/springconfig.xml");
If you are unsure where your springconfig.xml ends up after you have built your application, you can use the following command to list the contents of your jar:
jar -tvf myapp.jar
For a default eclipse java project, the project-home/bin directory is the start of the classpath.
A related question was asked here
-
I did the same and put application context xml in src directory. It does not work. I am working on Eclipse RCP application. – itun May 13 '12 at 15:07
-
Updated to include some class path debug ideas. I tested this with Eclipse using src/config/springconfig.xml and it works for me. – pd40 May 15 '12 at 10:01
Use ClassPathXmlApplicationContext
:
ApplicationContext ctx =
new ClassPathXmlApplicationContext("applicationContext.xml");
Or consider migrating to @Configuration
:
ApplicationContext ctx =
new AnnotationConfigApplicationContext(AppConfig.class);
where AppConfig
is annotated with @Configuration
and no XML is needed.

- 334,321
- 69
- 703
- 674
-
I did the same and put application context xml in src directory. It does not work – itun May 13 '12 at 13:53
-
1@itun: please explain "*does not work*". If you are using [tag:maven], the `applicationContext.xml` should be in `src/main/resources`. If not - somewhere in the root directory of your CLASSPATH. – Tomasz Nurkiewicz May 13 '12 at 13:54
Check this example Spring Setter Injection
If the XML is in the applications classpath then use like this
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Otherwise if the XML is in File system then use
ApplicationContext context = new FileSystemXmlApplicationContext("beans.xml");

- 2,812
- 1
- 20
- 13