在实际项目开发中发现不管是在普通Spring还是SpringBoot项目中的WebSocket主类中使用@Autowired都没办法注入想要的对象,现针对这两种情况记录一下解决办法。
1、在普通Spring项目中的WebSocket主类中如何注入对象:
IBusinessService businessService = (IBusinessService )ContextLoader.getCurrentWebApplicationContext().getBean("businessService")
2、在SpringBoot项目中的WebSocket主类中如何注入对象:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
//如果在webscoket主类中不需要autowired,则下面这个函数就不需要了
@Bean
public YaoEndpointConfigure newConfigure()
{
return new YaoEndpointConfigure();
}
}
import javax.websocket.server.ServerEndpointConfig;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* 这个类的核心就是getEndpointInstance(Class clazz)这个方法。
* 定义了获取类实例是通过ApplicationContext获取。
* 当WebSocketMain需要使用@Autowired引入其他实例时,需要在@ServerEndpoint注解中添加
* configurator=YaoEndpointConfigure.class
* @author caochunfang
*
*/
public class YaoEndpointConfigure extends ServerEndpointConfig.Configurator
implements ApplicationContextAware{
private static volatile BeanFactory context;
@Override
public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException
{
return context.getBean(clazz);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
YaoEndpointConfigure.context = applicationContext;
}
}
@Component
@ServerEndpoint(value="/wss/{uuid}",configurator = YaoEndpointConfigure.class)
public class WebSocketMain {
private static final Logger log = LoggerFactory.getLogger(WebSocketMain.class);
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static AtomicInteger onlineCount = new AtomicInteger(0);
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketMain> webSocketSet = new CopyOnWriteArraySet<WebSocketMain>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
@Autowired
private IYaoService yaoService;
//上面仅仅是代码片段
仅凭本人项目经验而谈,如有建议还请不吝赐教☺