spring和servlet

本文介绍两种在Servlet中获取Spring注入对象的方法:一是利用WebApplicationContextUtils工具类;二是自定义Listener实现上下文加载。

在servelt中取得spring注入对象的方法

方法1:

1、先在web.xml中定义加载applicationContext.xml的listener 

2、在servlet中可用此取得User对象 
WebApplicationContext   ctx=WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext()); 
User   user   =   (User)ctx.getBean( "user "); 
String   userName   =   user.getUserName(); 

方法二:

1.在web.xml中自定义一个listener

<!-- listener初始化spring注入 -->
	<listener>
		<listener-class>cn.com.cardinfo.report.tools.listener.ContextListener</listener-class>
	</listener>

2.自定义listener的写法

package cn.com.cardinfo.report.tools.listener;
import javax.servlet.*;
import cn.com.cardinfo.report.tools.main.MainCase;
import java.util.*;


public class ContextListener implements ServletContextListener {
	public void contextInitialized(ServletContextEvent event) {
		MainCase.init(); //初始化加载spring的方法
	}


	public void contextDestroyed(ServletContextEvent event) {
		
	}
}
3.自定义init方法  这是一个取巧的方法,在web.xml中自定义一个listener并在监听容器启动的时候加载init方法

init是一个在类中指定ApplicationContext.xml中profile获得context的方法

这样,做完之后,就会在容器加载的时候,就获取到context(这个方法之只用于 因为某种原因,spring不能自定注入的特殊案例)

	private static ApplicationContext context;
	public static ReportDataBean process(String path) throws Exception {

		// 获得导入导出控制类
		Controller controller = context.getBean(Controller.class);
		// 处理路径为服务器上的upload文件夹
		ReportDataBean bean = controller.process(path);
		return bean;

	}

	public static void init() {
		if (context == null) {
			System.setProperty("spring.profiles.active", "production");
			context = new ClassPathXmlApplicationContext(
					"classpath:applicationContext.xml");
		}
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值