对于Spring对websocket的属性注入失败问题,困扰我一天,最后终于解决了

时间:2025-04-20 18:56:01

首先导入包必须的:

<!-- /artifact//spring-websocket -->
	<dependency>
	    <groupId></groupId>
	    <artifactId>spring-websocket</artifactId>
	    <version>4.3.</version>
	</dependency>

以及一个

下面看代码


package ;

import ;
import ;
import ;
import ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;

import ;
import ;
import ;
@ServerEndpoint(value="/websocket/{playerId}",configurator = )
public class WebSocketController {
	
	@Resource
	private PlayerDaoImpl playerDao;
	
	@Resource()
	private SessionFactory sessionFactory;
	/**
	 * 用来存放所有的在线用户
	 */
	private static final Map<String,WebSocketController> connections = new LinkedHashMap<String, WebSocketController>();
	
	/**
	 * 获取用户传过来的用户信息
	 */
	private Session session;
	
	/**
	 * 连接websocket成功
	 * @param playerId
	 * @param session
	 */
	@OnOpen
	public void onOpen(@PathParam("playerId") String playerId, Session session){
		 = session;
		(());
		(playerId+"打开了连接!!!");
		(playerId, this);
		Map<String, String> msg = new HashMap<String, String>();
		("title", "pId_check");
		("result", "success");
		sendMessage(playerId, (msg));
		
		/***********  下面的问题  *************/
		(playerDao);
		Player playerInfo = (playerId);
		(playerInfo);
		Map<String, Object> playerInfoMap = new HashMap<String, Object>();
		("title", "playerInfo");
		("info", playerInfo);

		//sendMessage(playerId, (playerInfoMap));
	}

	/**
	 * 接受客服端发送的消息
	 * @param playerId 发送消息的ID
	 * @param message 消息
	 * @param session
	 */
	@OnMessage
	public void OnMessage(@PathParam("playerId") String playerId, String message, Session session){
		(message);
		sendMessage(playerId, "收到消息了");
	}
	
	/**
	 * 向客户端发送消息
	 * @param playerId 当前用户ID
	 * @param message 消息内容
	 */
	public void sendMessage(String playerId,String message) {
		try {
			if ((playerId)) {
				().sendText(message);
			}
		} catch (IOException e) {
			();
		}
	}
	/**
	 * 用户关闭连接
	 * @param playerId
	 * 移除当前ID的session
	 */
	@OnClose
	public void onClose(@PathParam("playerId") String playerId) {
		(playerId + " 已掉线!");
		(playerId);
	}
	/**
	 * 发送错误!!!
	 * @param playerId
	 * @param session
	 * @param error
	 * 移除当前ID的session
	 */
	@OnError
	public void onError(@PathParam("playerId") String playerId, Session session, Throwable error) {
		("websocket onerror - " + playerId);
		(playerId);
		();
	}

}

主要在@ServerEndpoint设置: configurator =  

意思是可以Spring注入,就这么简单