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#


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM