您的位置:首页 > 编程语言 > Java开发

spring如何把service注入listener或者filter?

2016-06-19 15:12 465 查看
spring如何把service注入listener?
答案是不可以。
但listener中需要使用service方法怎么办?
下面介绍三种方式:1、用qurartz的一次性任务的实现方式 2、 也可以用下面的方式来获取applicationContext,然后自己加载bean。3、 还可以自己解析配置文件,单独生成一个context,但这样浪费太大,不建议这样做。

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

public void contextInitialized(ServletContextEvent arg0) {
ServletContext context = arg0.getServletContext();
ApplicationContext ctx = WebApplicationContextUtils
.getWebApplicationContext(context);
ArticleInfoService articleinfoService = (ArticleInfoService) ctx
.getBean("articleinfoService");
articleinfoService.init();
}

在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了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: