在 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");