【问题标题】:Using ApplicationContext in Spring MVC.在 Spring MVC 中使用 ApplicationContext。
【发布时间】:2012-04-04 19:41:04
【问题描述】:

我有一个 spring.xml 文件,其中列出了所有 bean 定义,其中我列出了使用 beans、指定 messageSource、dataSource 等的所有依赖项。此外,我还有一个类 ApplicationContext 类,其中 iam 使用上下文获取所有豆子。 代码是::

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));

    }

}

我有一个应用程序上下文用于访问与 JDBC 模板相关的 bean 的 Dao 类。我现在必须使用 spring MVC 开发一个 Web 应用程序,并且我需要使用这个 applicationContext。我如何在 SpringMVC 中使用这些 applicationContext 类。我知道我需要使用 applicationcontextlisteners 但在哪里写呢?谢谢。。

【问题讨论】:

    标签: spring spring-mvc applicationcontext


    【解决方案1】:

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

    <servlet>
        <servlet-name>yourapp</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    

    然后在您的 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>
    

    然后在你的 WEB-INF 中添加 applicationContext.xml 和你的 bean。

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

    【讨论】:

      猜你喜欢
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-11
      • 2012-07-27
      • 2022-01-17
      • 1970-01-01
      • 2011-06-27
      相关资源
      最近更新 更多