在 Spring MVC 中使用 ApplicationContext。
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10018127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using ApplicationContext in Spring MVC.
提问by Shantanu Tomar
I have a spring.xml file where in all the bean definitions are listed, where i have listed all the dependencies using beans, specified messageSource, dataSource etc. Also i have a class ApplicationContext class where iam using the context to get all the beans. The code is ::
我有一个 spring.xml 文件,其中列出了所有 bean 定义,其中我列出了使用 bean、指定消息源、数据源等的所有依赖项。此外,我还有一个类 ApplicationContext 类,其中我使用上下文来获取所有 bean。代码是::
package models;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ApplicationContextClass {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
AbstractApplicationContext context = new ClassPathXmlApplicationContext("Spring.xml");
context.registerShutdownHook();
ATTModel attmodel = (ATTModel) context.getBean("att");
//ProjectModel project = (ProjectModel)context.getBean("project");
//project.call1();
attmodel.call();
System.out.println(context.getMessage("insertiondone",null, "Default greeting",null));
}
}
and i have Dao class where an applicationContext is used to access JDBCtemplate related bean. I have to develop a web application now using spring MVC and i need to use this applicationContext. How can i use these applicationContext classes in SpringMVC. I knw i need to use applicationcontextlisteners but where to write them ? Thanks..
我有 Dao 类,其中 applicationContext 用于访问与 JDBCtemplate 相关的 bean。我现在必须使用 spring MVC 开发一个 web 应用程序,我需要使用这个 applicationContext。我如何在 SpringMVC 中使用这些 applicationContext 类。我知道我需要使用 applicationcontextlisteners 但在哪里编写它们?谢谢..
回答by chalimartines
You have two ways. In web.xml define this.
你有两种方法。在 web.xml 中定义这个。
<servlet>
<servlet-name>yourapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
And to your WEB-INF folder add yourapp-servlet.xml with your beans and mvc configuration.
并在您的 WEB-INF 文件夹中添加 yourapp-servlet.xml 以及您的 bean 和 mvc 配置。
Other way is. In web.xml define this.
另一种方式是。在 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>
And to your WEB-INF add applicationContext.xml with your beans.
并在您的 WEB-INF 中添加 applicationContext.xml 和您的 bean。
You can also combine these approaches.
您也可以结合使用这些方法。

