在WebSocket类中无法引用其他类方法

本文详细介绍了在SpringBoot项目中解决WebSocket无法注入其他类的问题。通过创建自定义的YaoEndpointConfigure类,并在配置处理器中注册,可以实现在WebSocket中使用Spring管理的bean。具体步骤包括编写配置类、修改处理器配置和WebSocket类注解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解决:

1.Spring Cloud/Boot WebSocket 无法注入其他类的解决办法https://blog.csdn.net/tornadojava/article/details/78781474

2.Spring和SpringBoot项目中的WebSocket中引用对象的不同写法https://blog.csdn.net/eric520zenobia/article/details/84955250

第一步:编写 YaoEndpointConfigure 类

package boot.spring.config;


import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.websocket.server.ServerEndpointConfig;

public class YaoEndpointConfigure extends ServerEndpointConfig.Configurator
        implements ApplicationContextAware {

    private static volatile BeanFactory context;

    @Override
    public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException
    {
        return context.getBean(clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        YaoEndpointConfigure.context = applicationContext;
    }
}

第二步:在websocket配置处理器中填写

@Bean
    public YaoEndpointConfigure newConfigure()
    {
        return new YaoEndpointConfigure();
    }

第三步:修改MyWebSocket的注解

@ServerEndpoint(value = "XX",configurator = YaoEndpointConfigure.class)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值