WebSocket Scope
每个 WebSocket 会话都有一个属性映射。该映射以标头的形式附加到入站客户端消息,并且可以从控制器方法中访问,如下面的示例所示:
Each WebSocket session has a map of attributes. The map is attached as a header to inbound client messages and may be accessed from a controller method, as the following example shows:
@Controller
public class MyController {
@MessageMapping("/action")
public void handle(SimpMessageHeaderAccessor headerAccessor) {
Map<String, Object> attrs = headerAccessor.getSessionAttributes();
// ...
}
}
您可以在 websocket
作用域中声明一个 Spring 托管的 Bean。您可以将 WebSocket 作用域的 Bean 注入到控制器和注册在 clientInboundChannel
上的任何通道拦截器中。它们通常是单例,并且比任何单独的 WebSocket 会话存活时间更长。因此,您需要对 WebSocket 作用域的 bean 使用作用域代理模式,如下面的示例所示:
You can declare a Spring-managed bean in the websocket
scope.
You can inject WebSocket-scoped beans into controllers and any channel interceptors
registered on the clientInboundChannel
. Those are typically singletons and live
longer than any individual WebSocket session. Therefore, you need to use a
scope proxy mode for WebSocket-scoped beans, as the following example shows:
@Component
@Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyBean {
@PostConstruct
public void init() {
// Invoked after dependencies injected
}
// ...
@PreDestroy
public void destroy() {
// Invoked when the WebSocket session ends
}
}
@Controller
public class MyController {
private final MyBean myBean;
@Autowired
public MyController(MyBean myBean) {
this.myBean = myBean;
}
@MessageMapping("/action")
public void handle() {
// this.myBean from the current WebSocket session
}
}
与任何自定义作用域一样,Spring 在第一次从控制器访问 MyBean
实例时对其进行初始化,并将该实例存储在 WebSocket 会话属性中。随后的返回是同一个实例,直到会话结束。WebSocket 作用域的 bean 具有所有 Spring 生命周期方法被调用,如前面的示例所示。
As with any custom scope, Spring initializes a new MyBean
instance the first
time it is accessed from the controller and stores the instance in the WebSocket
session attributes. The same instance is subsequently returned until the session
ends. WebSocket-scoped beans have all Spring lifecycle methods invoked, as
shown in the preceding examples.