Problem with java websocket using @Autowired to inject null

The SpringBoot project integrates websocket, and after establishing the connection, it is found that NullException is automatically injected.

Because spring is a singleton and websocket is a multi-object (an object is generated every time a connection is established)

So when the project starts, the websocket will be initialized and injected into the spring container. The service injected at this time is not null, but spring is a singleton, so it will only be injected once. When the websocket connection is established again, this time The object is NullException.

Solution: You can get the beans through the spring context

Get the context tool class:

@Component
public class SpringContextUtil implements ApplicationContextAware {


    /**
     * Print log
     */
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * Get the context object
     */
    private static ApplicationContext applicationContext;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
        logger.info("set applicationContext");
    }

    /**
     * Get applicationContext
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * Get the bean object by name
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {

        return getApplicationContext().getBean(name);
    }

    /**
     * Get the bean object through class
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * Get the specified bean object through name, clazz
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}

Used in business code:

@Component
@ServerEndpoint(value = "/socket/{group}/{user}/{sessionId}")
@Slf4j
public class WebSocketServer {

    private static AtomicInteger onlineCount = new AtomicInteger(0);

    private static final int MAX_CONNECT = 500;

    private MsgGroupEnum group;

    private String user;

    private Session session;

    private String sessionId;

    public AppDataService getAppData() {
        return SpringContextUtil.getBean(AppDataService.class);
    }

}

Guess you like

Origin blog.csdn.net/weixin_43005845/article/details/119819231