spring使用WebSocket注入service层失败

这里spring集成的是javax包下的WebSocket,出现了注入service层的异常,如果是使用spring-websocket则没有这个问题。

spring集成javax包下的WebSocket需要配置ServerEndpointExporter实例。

<bean class="org.springframework.web.socket.server.standard.ServerEndpointExporter"/>

这样注入service层失败,调用userService是报空指针异常,注入失败:

@Autowired
    private IUserService userService;

原因:当有连接接入时,会创建一个新的服务器类对象,而spring只会给IOC容器启动时创建的对象注入userService,连接接入时创建的对象并没有注入,如下实验:

@Component
@ServerEndpoint(value = "/javaconver/{id}")
public class Conversation {
    @Autowired
    private IUserService userService;


    //concurrent包的线程安全,用来存放每个客户端对应的WebSocket
    private static ConcurrentHashMap<String, Conversation> sockets = new ConcurrentHashMap<>();

    @OnOpen
    public void open(Session session, @PathParam("id")String id){
        sockets.put(id,this);
        System.out.println(sockets);
    }
}

这是写了两个页面连接的结果:

可见确实是两个不同的对象。

解决方法: 

将userService设为静态变量,但是要注意:

@Autowired
    private static IUserService userService;

这样写仍然会报空指针异常,因为spring不会给静态变量注入

正确写法:

@Component
@ServerEndpoint(value = "/javaconver/{id}")
public class Conversation {
    private static IUserService userService;

    @Autowired
    public void setUserService(IUserService userService) {
        System.out.println("执行seter方法");
        this.userService = userService;
        System.out.println(this.userService);
    }
    //concurrent包的线程安全,用来存放每个客户端对应的WebSocket
    private static ConcurrentHashMap<String, Conversation> sockets = new ConcurrentHashMap<>();

    @OnOpen
    public void open(Session session, @PathParam("id")String id){
        sockets.put(id,this);
        System.out.println(sockets);
        System.out.println(sockets.get(id).userService);
        System.out.println(Conversation.userService);
    }

    @OnMessage(maxMessageSize = 56666)
    public void message(String str, Session session){
        userService.out();
    }
}

 执行结果:

 

 水平有限,错误之处还请指正!

  • 8
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值