启动类main方法中改造
public static void main(String[] args) {
//SpringApplication.run(EResourceApplication.class, args);
//解决webSocket中service类无法注入的问题
SpringApplication springApplication = new SpringApplication(EResourceApplication.class);
ConfigurableApplicationContext configurableApplicationContext = springApplication.run(args);
WebSocketServer.setApplicationContext(configurableApplicationContext);
System.out.println("ヾ(◍°∇°◍)ノ゙物联网数据平台系统启动成功 ! ヾ(◍°∇°◍)ノ゙");
}
WebSocketServer服务类中改造
//由于Autowired注解和ServerEndpoint注解同时使用会冲突
// 所以使用原生方法获取bean;
private static ApplicationContext applicationContext;
private IEquipmentService equipmentService;
public static void setApplicationContext(ApplicationContext applicationContext){
WebSocketServer.applicationContext=applicationContext;
}
onOpen方法中改造
equipmentService = SpringContextUtil.getBean(IEquipmentService.class);
自己拷贝过去工具类代码
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* @author haotongkun
* @date 2021/8/9 17:32
* @Description TODO
* @Version 1.0
*/
@Component
public class SpringContextUtil implements ApplicationContextAware {
/**
* 上下文对象实例
*/
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 获取applicationContext
*
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 获取HttpServletRequest
*/
public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
public static String getDomain(){
HttpServletRequest request = getHttpServletRequest();
StringBuffer url = request.getRequestURL();
return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
}
public static String getOrigin(){
HttpServletRequest request = getHttpServletRequest();
return request.getHeader("Origin");
}
/**
* 通过name获取 Bean.
*
* @param name
* @return
*/
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
/**
* 通过class获取Bean.
*
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
/**
* 通过name,以及Clazz返回指定的Bean
*
* @param name
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}