Using ApplicationContext in Spring MVC.

江枫思渺然 提交于 2019-12-12 13:09:05

问题


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 ::

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..


回答1:


You have two ways. In web.xml define this.

<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.

Other way is. In web.xml define this.

<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.

You can also combine these approaches.



来源:https://stackoverflow.com/questions/10018127/using-applicationcontext-in-spring-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!