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/
-----------------------------------