码迷,mamicode.com
首页 > 编程语言 > 详细

spring 整合websocket过程中遇到的问题

时间:2015-09-07 16:56:19      阅读:354      评论:0      收藏:0      [点我收藏+]

标签:

写了一个告警推送的websocket,由于类中用到了其它bean所以自然的用@Autowired注解将bean注入:
@ServerEndpoint(value = "/alarm/{id}", configurator = SpringConfigurator.class)
public class AlarmEndpoint {

    @Autowired
     private AlarmSimulator alarmSimulator;
     @OnOpen
     public void onOpen(Session session, @PathParam(value = "id") Long id) {
        .....
    }
}
调试过程中发现onOpen函数中的alarmSimulator 的值是null,说明注入失败了。

随后想到用构造函数的方法试试:
    @Autowired
    public AlarmEndpoint(AlarmSimulator alarmSimulator){
        this.alarmSimulator = alarmSimulator;
    }
结果启动时报错,看了看错误信息,应该是初始化endpoint时要调用无参数的构造函数。

随后在网上查到不能用自动注入的方式,用代码获取bean。
ContextLoader.getCurrentWebApplicationContext().getBean("name")
但是死活找不到alarmSimulator

又发现有人说这样可以拿到注解注入的bean
public class SpringContextUtil implements ApplicationContextAware {
 private static ApplicationContext applicationContext;
 @Override
 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  SpringContextUtil.applicationContext = applicationContext;
 }
 public static Object getBean(String name){
  applicationContext.getBeanDefinitionNames();
  return applicationContext.getBean(name);
 }
}
然后把此类注入的spring的配置文件中,但是情况跟上面一样,找不到bean。调试了一下发现,貌似这种方法找到的bean都是在applicationContext.xml中定义的,

所以想到在springMVC.xml中注入上面定义的类,顺利拿到alarmSimulator。看来getCurrentWebApplication.getBean方法拿不到也是这个问题。

得到结论,spring对applicationContext.xml中的bean和spring mvc中的bean是分开管理的,应该有两个applicationContext。

spring 整合websocket过程中遇到的问题

标签:

原文地址:http://my.oschina.net/u/2453016/blog/502372

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!