[英]Where to put Spring applicationContext.xml in a non-web application?
I am creating an application which uses Spring beans and I need to initialize ApplicationContext
from xml
. 我正在创建一个使用Spring bean的应用程序,并且需要从xml
初始化ApplicationContext
。 As it is not a server application, it doesn't have WEB-INF
folder.So, where I should put the xml
file? 由于它不是服务器应用程序,因此没有WEB-INF
文件夹。那么,我应该把xml
文件放在哪里?
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 Spring文档中有关应用程序上下文配置的便捷起点在此处
A file system xml application context is probably the easiest to start with. 文件系统xml应用程序上下文可能是最容易开始的。 So: 所以:
ApplicationContext appCtx =
new FileSystemXmlApplicationContext("/path/to/springconfig.xml");
Use ClassPathApplicationContext
if you have the xml configuration in your application class path. 如果您的应用程序类路径中具有xml配置,请使用ClassPathApplicationContext
。 In this example it might be a springconfig.xml under a project directory src/config/springconfig.xml. 在此示例中,它可能是项目目录src / config / springconfig.xml下的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: 如果您不确定在构建应用程序后springconfig.xml会在哪里结束,则可以使用以下命令列出jar的内容:
jar -tvf myapp.jar
For a default eclipse java project, the project-home/bin directory is the start of the classpath. 对于默认的Eclipse Java项目, project-home / bin目录是类路径的开始。
Use ClassPathXmlApplicationContext
: 使用ClassPathXmlApplicationContext
:
ApplicationContext ctx =
new ClassPathXmlApplicationContext("applicationContext.xml");
Or consider migrating to @Configuration
: 或者考虑迁移到@Configuration
:
ApplicationContext ctx =
new AnnotationConfigApplicationContext(AppConfig.class);
where AppConfig
is annotated with @Configuration
and no XML is needed. 使用@Configuration
注释AppConfig
地方,不需要XML。
Check this example Spring Setter Injection 检查此示例Spring Setter Injection
If the XML is in the applications classpath then use like this 如果XML位于应用程序的类路径中,则使用如下所示
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Otherwise if the XML is in File system then use 否则,如果XML在文件系统中,则使用
ApplicationContext context = new FileSystemXmlApplicationContext("beans.xml");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.