Spring工具类,提供取得Spring配置文件中定义的Bean的方法

 

       在 java EE 工程中,经常会用到定时任务Job、自定义servlet,在这些job、servlet中,也会用到在 spring 容器中声明的bean,如 service、dao等。

       在 job、servlet 中,这些 bean 的获取如下所示:

 

1. 自定义spring加载器

          这个加载器的作用就是把 ApplicationContext 装载到 SpringUtil 中。

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * @ClassName: SpringContextLoaderListener
 * @deprecated: 自定义spring加载器,把ApplicationContext装载到SpringUtil
 * @author 
 * @company 
 * @date 2014-5-15
 * @version V1.0
 */

public class SpringContextLoaderListener extends ContextLoaderListener {

	public void contextInitialized(ServletContextEvent event) {

		// 初始化父类 ContextLoaderListener
		super.contextInitialized(event);

		ServletContext context = event.getServletContext();

		ApplicationContext ctx = WebApplicationContextUtils
				.getRequiredWebApplicationContext(context);

		// 装载 SpringUtil 中的 ApplicationContext
		new SpringUtil().setApplicationContext(ctx);
	}
}

 

2. 将 SpringContextLoaderListener 加入 web.xml

 

注释 org.springframework.web.context.ContextLoaderListener

 

添加 SpringContextLoaderListener 



 

3. Spring工具类

   这个类的作用就是获取在 spring 容器中声明的 bean

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @ClassName: SpringUtil
 * @deprecated: Spring工具类,提供取得Spring配置文件中定义的Bean的方法
 * @author 
 * @company 
 * @date 2014-5-15
 * @version V1.0
 */

public class SpringUtil implements ApplicationContextAware {

	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext arg0)
			throws BeansException {

		// 在 SpringContextLoaderListener 中调用此方法

		SpringUtil.applicationContext = arg0;
	}

	public static Object getBean(String name) {
		
		// applicationContext 已在 SpringContextLoaderListener 中装载

		return applicationContext.getBean(name);
	}
}

 

4. 在 servlet 或者 job 中获取 spring 容器中声明的 bean

private HwSysParamsService hwSysParamsService;

hwSysParamsService = (HwSysParamsService) SpringUtil
					.getBean("hwSysParamsService");

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值