Method of calling service and mapper when SpringBoot integrates WebSocket

Scenes

SpringBoot+Vue integrates WebSocket to implement front-end and back-end message push:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/114392573

SpringCloud (if the microservice version is used as an example) integrates WebSocket to implement message push between the front and back ends:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/114480731

When integrating the websocket above, if you need to call the service and mapper methods of other services in the callback method of the websocket to establish a connection, the injection fails and the service is empty.

the reason:

When the project is initialized, it will initialize the websocket (not connected by the user), and spring will inject service for it at the same time. The service of the object is not null and is successfully injected. However, since spring manages singletons by default, only one service will be injected.
When a new user enters the chat, the system creates a new websocket object. At this time, a contradiction arises: Spring manages all singletons, and does not inject service into the second websocket object, so as long as it is created by the user connection The websocket object can no longer be injected.

Note:

Blog:
https://blog.csdn.net/badao_liumang_qizhi
Follow the public
account Domineering
programmers Get programming-related e-books, tutorial pushes and free downloads.

achieve

First, add the applicationContext attribute and set method to the websocket service class

    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }

Add location

 

Then in the startup class of the project

        ConfigurableApplicationContext applicationContext =   SpringApplication.run(RuoYiFzysControlApplication.class, args);
        WebSocketService.setApplicationContext(applicationContext);

Assign a value to it after the project is started. The WebSocketService here corresponds to the above own websocket service class

 

Then you can pass

applicationContext.getBean(IBusAreaControlService.class);

To call other services

Guess you like

Origin blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/114829426