在Spring MVC中使用ApplicationContext。

4

我有一个名为spring.xml的文件,在其中列出了所有bean定义,我使用bean列出了所有依赖项,指定了messageSource、dataSource等。此外,我有一个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));

    }

}

我有一个Dao类,其中使用了applicationContext来访问JDBCtemplate相关的bean。现在我需要使用Spring MVC开发Web应用程序,并且需要使用这个applicationContext。如何在SpringMVC中使用这些applicationContext类?我知道我需要使用applicationcontextlisteners,但是在哪里编写它们呢?谢谢。

1个回答

5
您有两种方法。在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配置在其中。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接