java监听器中如何获取Spring中的bean

更新时间:2016-04-15 09:53:36 点击次数:2237次

在web项目中监听是不能直接获取spring的bean的,我们只能通过代码来获取,我这边的应用场景是在监听中写了一个socket,socket获取数据后需要操作数据库,直接spring注解注意的话会实例化失败,获取为null,所以只能获取servlet中的context来使用bean。

spring中注入代码是:

1
2
    <bean id="trService" class="com.zbrx.bzy.service.TeacherService"></bean>
    <bean id="cdService" class="com.zbrx.bzy.service.ChildService"></bean>

然后我需要在监听程序中获取:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
WebApplicationContext applicationContext = 
        WebApplicationContextUtils.getWebApplicationContext(sc.getServletContext());
        this.trService=(TeacherService)applicationContext.getBean("trService");   
        this.cdService=(ChildService)applicationContext.getBean("cdService");  
 
//定义变量
 private TeacherService trService;
    private ChildService cdService;
    public TeacherService getTrService() {
        return trService;
    }
 
    public void setTrService(TeacherService trService) {
        this.trService = trService;
    }
 
    public ChildService getCdService() {
        return cdService;
    }
    public void setCdService(ChildService cdService) {
        this.cdService = cdService;
    }

这样就可以在你的监听中使用service来处理业务了。


本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责,本站只提供参考并不构成任何投资及应用建议。本站是一个个人学习交流的平台,网站上部分文章为转载,并不用于任何商业目的,我们已经尽可能的对作者和来源进行了通告,但是能力有限或疏忽,造成漏登,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

回到顶部
嘿,我来帮您!