在 Spring MVC 中使用 ApplicationContext。

Sha*_*mar 4 spring spring-mvc applicationcontext

我有一个 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));

    }

}
Run Code Online (Sandbox Code Playgroud)

我有 Dao 类,其中 applicationContext 用于访问与 JDBCtemplate 相关的 bean。我现在必须使用 spring MVC 开发一个 web 应用程序,我需要使用这个 applicationContext。我如何在 SpringMVC 中使用这些 applicationContext 类。我知道我需要使用 applicationcontextlisteners 但在哪里编写它们?谢谢..

cha*_*nes 5

你有两种方法。在 web.xml 中定义这个。

<servlet>
    <servlet-name>yourapp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
Run Code Online (Sandbox Code Playgroud)

并在您的 WEB-INF 文件夹中添加 yourapp-servlet.xml 以及您的 bean 和 mvc 配置。

另一种方式是。在 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>
Run Code Online (Sandbox Code Playgroud)

并在您的 WEB-INF 中添加 applicationContext.xml 和您的 bean。

您也可以结合使用这些方法。