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了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章