socket中引入service层
@ServerEndpoint("/chat/room/group/{param}")
@Component
@Slf4j
public class MyWebsocketServer {
//错误引用
//@Autowired
// private SocketUserService socketUserService;
//错误引用
// ApplicationContext act = ApplicationContextRegister.getApplicationContext();
// SocketUserService socketUserService = act.getBean(SocketUserService.class);
// 正确引用
public static SocketUserService socketUserService;
/**
* 存放所有在线的客户端
*/
private static Map clients = new ConcurrentHashMap();
private Gson gson = new Gson();
@OnOpen
public void onOpen(Session session,@PathParam("param")String socketUserId) {
log.info("有新的客户端连接了: {}", session.getId());
SocketUser socketUser = socketUserService.getSocketUser(Long.valueOf(socketUserId));
System.out.println(socketUser);
}
}
在配置类中写入
@Configuration
public class WebsocketConfiguration {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
//添加下面配置 在socket引入socketUserService
@Autowired
public void socketUserService(SocketUserService socketUserService){
MyWebsocketServer.socketUserService = socketUserService;
}
}
注意:这步写完有极大可能报错
could not initialize proxy - no Session
错误解析
- 去网上找资料,就是说因为 hibernate(这里是 Spring Data JPA ) 跟 spring 整合以后,hibernate 的 session 就交给 spring 管理了,请求进来的时候打开 session,请求完成的时候关闭 session。当我们想要使用懒加载去获取数据的时候,这时候原先的那个 session 已经关闭了,不能再获取数据了。由此,spring专门为这种情况作了一个过滤器 org.springframework.orm.hibernate4.support.OpenSessionInViewFilter。它可以把hibernate的session的声明周期维持在视图的开启和关闭之间。这样,只要我们这个视图没有关闭,我们就可以通过 ajax 来使用懒加载获取数据
- 在配置文件中加入
- .yml配置
spring:
jpa:
properties:
hibernate:
enable_lazy_load_no_trans: true
- .properties配置
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true