Reputation: 3521
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?
Upvotes: 1
Views: 12249
Reputation: 3247
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
Upvotes: 3
Reputation: 2812
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");
Upvotes: 1
Reputation: 340733
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.
Upvotes: 3