简体   繁体   English

如何在Struts2中获取Springs ApplicationContext?

[英]how to get Springs ApplicationContext in Struts2?

I have a struts2 Web project with Spring plugin. 我有一个带有Spring插件的struts2 Web项目。 The applicationContext.xml is sitting at applicationContext.xml位于

/WEB-INF/applicationContext.xml

How would I acces it inside my class 我如何在课堂上上课

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

does not seem to work. 似乎不起作用。

You're not really going about this the correct way as you shouldn't be loading the application context. 您实际上并不是在以正确的方式进行操作,因为您不应该加载应用程序上下文。 However, have you tried: 但是,您是否尝试过:

new ClassPathXmlApplicationContext("classpath:applicationContext.xml");

I would suggest that you add the following to your web.xml: 我建议您将以下内容添加到web.xml中:

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

This will ensure that the Spring IOC container is initialised when your application starts. 这将确保在您的应用程序启动时初始化Spring IOC容器。 You can then use Spring to provide your actions with the necessary dependencies wired in. You shouldn't need to get hold of the IOC container as you are doing since this is not dependency injection. 然后,您可以使用Spring为您的操作提供必要的依赖关系。您不需要像现在那样握住IOC容器,因为这不是依赖关系注入。

Only files under WEB-INF/classes would come under classpath. 只有WEB-INF/classes下的文件才会在classpath下。 You should better move it to WEB-INF/classes directory. 您最好将其移动到WEB-INF/classes目录。

You can also load the context file from your web.xml using one of Spring context listeners. 您还可以使用Spring上下文侦听器之一从web.xml加载上下文文件。 Can you explain why you are loading Spring config into your webapp? 您能解释一下为什么要将Spring config加载到webapp中吗? That would give us a better idea to suggest. 那会给我们一个更好的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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