在websocket中失效的@autowired

@ServerEndpoint(value = "/websocketClient/{userId}")
@Component
@Slf4j
public class WebSocketClient {
    @Autowired
    IBotQuestionLlmService llmService;
}

上述代码使用了@Component注解,正常来说他会标记一个类为spring管理的bean,可以让我们正常使用依赖注入。

但其实同时使用serverEndpoint和component会有两个可能

1.双重实例化:websocket容器会实例化一个对象处理websocket请求;spring也会实例一个bean。这回导致一个类有两个实例引起不一致行为

2.依赖注入失效:websocket容器实例化后不会进行spring的依赖注入,这样会导致即使使用了autowired,这些字段也不会被注入

 

如何解决because "this.service" is null问题

1.手动从spring上下文获取bean

  private static ApplicationContext context;

    private Service service;

    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
    public void test() {
        service= context.getBean(Service.class);
  }

 

public class WebSocketClient implements ApplicationContextAware {
    private static ApplicationContext context;

    private Service service;

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

 

2.继承springbeanAutowiringSupport(测试不生效)

public class WebSocketClient extends SpringBeanAutowiringSupport

 

posted @ 2025-03-18 16:31  天启A  阅读(39)  评论(0)    收藏  举报