websocket 服务器中注入 service 业务接口
创建公共Utils 类 ApplicationContextRegister
@Component
@Lazy(false)
public class ApplicationContextRegister implements ApplicationContextAware {
/*
* 设置spring上下文 * * @param applicationContext spring上下文 * @throws BeansException * author:huochengyan https://blog.youkuaiyun.com/u010919083
*/
private static ApplicationContext APPLICATION_CONTEXT;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
APPLICATION_CONTEXT = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return APPLICATION_CONTEXT;
}
}
websocket 使用service 层
ApplicationContext act = ApplicationContextRegister.getApplicationContext();
private CarRouteService carRouteService = act.getBean(CarRouteService.class);
carRouteService.add(carRoute);
本文介绍了一种在WebSocket服务器中注入并使用Spring框架下Service层业务接口的方法。通过创建一个公共的Utils类——ApplicationContextRegister,该类实现了ApplicationContextAware接口,用于在WebSocket中获取Spring上下文并访问Service层。具体实现包括定义静态ApplicationContext变量,实现setApplicationContext方法注册Spring上下文,以及提供getApplicationContext静态方法供外部调用。
957

被折叠的 条评论
为什么被折叠?



