須要在 springboot 某個業務類中注入 applicationContext,解決辦法以下spring
public static void main(String[] args) { ConfigurableApplicationContext configurableApplicationContext =SpringApplication.run(HongoneApplication.class, args); //解決WebSocket不能注入的問題 WebSocketServer.setApplicationContext(configurableApplicationContext); }
本地測試經過,可是打成 war 包後,發現注入失效,解決辦法以下springboot
public class HongoneApplication extends SpringBootServletInitializer{ public static void main(String[] args) { ConfigurableApplicationContext configurableApplicationContext =SpringApplication.run(HongoneApplication.class, args); //解決WebSocket不能注入的問題 WebSocketServer.setApplicationContext(configurableApplicationContext); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(HongoneApplication.class); } @Override public void onStartup(ServletContext servletContext) throws ServletException { super.onStartup(servletContext); WebSocketServer.setApplicationContext(WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)); }
啓動類中重寫以上兩個方法,問題解決app