zoukankan      html  css  js  c++  java
  • SpringBoot:WebSocket使用Service层的方法

    方法一:

    创建工具类 ApplicationContextRegister.java

    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.context.annotation.Lazy;
    import org.springframework.stereotype.Component;
    
    @Component
    @Lazy(false)
    public class ApplicationContextRegister  implements ApplicationContextAware {
        private static ApplicationContext APPLICATION_CONTEXT;
     
        /**
         * 设置spring上下文  *  * @param applicationContext spring上下文  * @throws BeansException  * author:huochengyan https://blog.csdn.net/u010919083
         */
     
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            APPLICATION_CONTEXT = applicationContext;
        }
     
        public static ApplicationContext getApplicationContext() {
            return APPLICATION_CONTEXT;
        }
    }

    逻辑代码中使用方式

    //websocket 使用service 层
                    ApplicationContext act = ApplicationContextRegister.getApplicationContext();
                    messagelogService=act.getBean(MessagelogService.class);
                    int resultlog = messagelogService.insertIntoMessagelog(messagelog); //.insertIntoMessagelog(messagelog)是我的方法

    方法二:

    引用spring-websocket 的包,使用@ServerEndpoint注解

    pom.xml

    <properties>
         <spring.version>4.0.5.RELEASE</spring.version>
    </properties>
    
    <dependencies>
    
      <dependency>
        <groupId>javax.websocket</groupId>
        <artifactId>javax.websocket-api</artifactId>
        <version>1.0</version>
        <scope>provided</scope>
      </dependency>
    
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-websocket</artifactId>
        <version>${spring.version}</version>
      </dependency>
    
    </dependencies>

    websocket实体类加注解

    //在websocket类添加configurator = SpringConfigurator.class
    //当创建好一个(服务)端点之后,将它以一个指定的URI发布到应用当中,这样远程客户端就能连接上它了
    @ServerEndpoint(value="/websockets",configurator = SpringConfigurator.class)
    public class MyWebSocket {
    
    }

     有网友说 configurator = GetHttpSessionConfiguratorNew.class 这个配置,大家也可以试试。

    文章转载至:https://blog.csdn.net/u010919083/article/details/79388720#

    ----------------------------------- 作者:怒吼的萝卜 链接:http://www.cnblogs.com/nhdlb/ -----------------------------------
  • 相关阅读:
    做人做事
    不骄不躁
    争取
    收入
    Windows 7下的Comodo Firewall免费防火墙
    成功水平
    成家立业
    Windows无法安装到GPT格式磁盘的根本解决办法
    安装Windows10操作系统
    安装操作系统的几种方式
  • 原文地址:https://www.cnblogs.com/nhdlb/p/14296932.html
Copyright © 2011-2022 走看看