Spring和SpringBoot项目中的WebSocket中引用对象的不同写法

在实际项目开发中发现不管是在普通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;


//上面仅仅是代码片段

仅凭本人项目经验而谈,如有建议还请不吝赐教☺

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值