普通java类获取application_javaWeb普通类获取ApplicationContext

网上看了很多关于获取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大方法,总有一款适合你。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值