listener或者filter注入service

listener中需要使用service方法怎么办?
解决方法:

1、用qurartz的一次性任务的实现方式

2、 也可以用下面的方式来获取applicationContext,然后自己加载bean。

3、 还可以自己解析配置文件,单独生成一个context,但这样浪费太大,不建议这样做。

下面贴上第二种方法的实现代码
在listener中

public class XXStartUpListener extends ContextLoaderListener {          @Override     public void contextInitialized(ServletContextEvent event)     {         ServletContext servletContext=event.getServletContext();         ApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(servletContext);         DcTimerService dcTimerService=(DcTimerService)ctx.getBean("dcTimerService");         QuartzManager quartzManager=(QuartzManager)ctx.getBean("quartzManager");         List<CustomJob> jobList=dcTimerService.findAll();         for (CustomJob customJob : jobList)         {             if("STARTED".equals(customJob.getStrStatus()))             {                              }             System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");         }     }      }

在filter或者jsp、servlet中类似,
使用HttpServletRequest获取SerlvetContext的方法是:request.getSession().getServletContext();

------------------------------------------------------------------------------------------------
另外扩展一下,spring定义的或者注解的各个bean,如何在普通类(没有被spring管理的类,比如自己new一个)中获取呢?
在spring中有一个org.springframework.context.ApplicationContextAware,只要继承并实现这个接口即可使用spring的全局context。
使用这个的前提是spring已经初始化完毕,所以在listener中还不能使用这个方法。
需要两个步骤:
1、实现这个接口

import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class GlobalContext implements ApplicationContextAware { private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext contex) throws BeansException { context = contex; } public static ApplicationContext getContext() { return context; } public final static Object getBean(String beanName) { return context.getBean(beanName); } public final static Object getBean(String beanName, Class<?> requiredType) { return context.getBean(beanName, requiredType); } }

2、把实现该接口的类,配置到spring的配置文件(application-all.xml)中。

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <!-- getGlobalContext --> <bean class="com.netease.extration.util.GlobalContext"></bean> </beans>

这样就可以在任何地方使用globalcontext来获取spring定义的bean了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章