网上看了很多关于获取ApplicationContext的方法,五大方法,但是我用web服务使用成功的就这一个,自己记忆下。import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
/**
* 获取ApplicationContext并调用
*/
public class StartListener implements ServletContextListener{
//这是一个类,就是通过xml方式能调用到这个类。必须是静态修饰
private static ItemService itemService;
public StartListener(){
super();
}
@Override
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
WebApplicationContext springContext=WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());//获取初始化的上下文
itemService = ( ItemService ) springContext.getBean( "item" );//可以传形参的方式改变想要获取的bean
}
/**
* 创建目录,这是调用上面类中的方法
* @param mkdirName
* @return
*/
public String mkdir(String mkdirName){
System.out.println("调用创建目录方法!!");
return itemService.mkdir(mkdirName);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
//销毁
}
}
xml中需要的设置:/p>
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
Archetype Created Web Application
contextConfigLocation
classpath:hsf-consumer-beans.xml
//用于监听刚刚配置的类
org.springframework.web.context.ContextLoaderListener
com.alibaba.edas.carshop.detail.StartListener
//下面是接口
IndexServlet
com.alibaba.edas.carshop.detail.IndexServlet
IndexServlet
/index.htm
关于获取ApplicationContext的方法,适用于我的是这个方法,其他几个方式你们也可以去试试。总共5大方法,总有一款适合你。