百度論壇里面有很多好的方法,借鑒.
重點:因為項目是StringBoot所以我用的是下面的方法很好使:
Service.... service = (Service....) ContextLoader.getCurrentWebApplicationContext().getBean(Service.....class);
ContextLoader.getCurrentWebApplicationContext().getBean(BeanName)
下面的是其他人的回答,第一個有用了,其他的先看看吧:
例子1:
當時 做開發的時候 在2015年7月份的時候 碰到跟樓主一樣的問題
網上找遍 都找不到自動注入的方法,最后沒辦法,在websocket的握手驅動類里面 返回一個能拿到注入權限的類,然后利用這個類 實現websocket接口 拿到自動注入權限。繞了他娘的好大一圈。
例子2:
今天也遇到了這個問題,找了半天也沒找到自動注入的方法。最后選擇的最原始的方法解決。下面是我的代碼 @Component @Lazy(false) public class ApplicationContextRegister implements ApplicationContextAware { private static ApplicationContext APPLICATION_CONTEXT; /** * 設置spring上下文 * * @param applicationContext spring上下文 * @throws BeansException */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { APPLICATION_CONTEXT = applicationContext; } public static ApplicationContext getApplicationContext() { return APPLICATION_CONTEXT; } } webScoket的注入service { ApplicationContext act = ApplicationContextRegister.getApplicationContext(); userService=act.getBean(UserService.class); chatService=act.getBean(ChatService.class); }
舉個自己寫過的例子:html+js+后台
<div class="View" style="width: 100%;height:100%;"> <h1>Java后端WebSocket的Tomcat實現</h1> Welcome<br/><input id="text" type="text"/> <button onclick="send()">發送消息</button> <hr/> <button onclick="closeWebSocket()">關閉WebSocket連接</button> <hr/> <div id="message"></div> </div>
js:
var websocket = null; //判斷當前瀏覽器是否支持WebSocket if ('WebSocket' in window) { websocket = new WebSocket("ws://localhost:8084/websocket"); } else { alert('當前瀏覽器 Not support websocket') } //連接發生錯誤的回調方法 websocket.onerror = function () { setMessageInnerHTML("WebSocket連接發生錯誤"); }; //連接成功建立的回調方法 websocket.onopen = function () { setMessageInnerHTML("WebSocket連接成功"); websocket.send(sessionStorage.getItem("dealerId")); } //接收到消息的回調方法 websocket.onmessage = function (event) { setMessageInnerHTML(event.data); } //連接關閉的回調方法 websocket.onclose = function () { setMessageInnerHTML("WebSocket連接關閉"); } //監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。 window.onbeforeunload = function () { closeWebSocket(); } //將消息顯示在網頁上 function setMessageInnerHTML(innerHTML) { document.getElementById('message').innerHTML += innerHTML + '<br/>'; } //關閉WebSocket連接 function closeWebSocket() { websocket.close(); } //發送消息 function send() { //var message = document.getElementById('text').value; websocket.send(sessionStorage.getItem("dealerId")); }
后台:
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>
參考,如果缺少包的話,還是的百度。
import java.util.concurrent.CopyOnWriteArraySet;
import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.ContextLoader;
import jy.api.form.JyChangeInStatusHistoryApiForm;
import jy.component.BaseController;
import jy.component.ServiceFacade;
import jy.service.JyChangeInStatusHistoryService;
@Component
@ServerEndpoint("/websocket")
public class WebsocketTest extends BaseController{
public WebsocketTest(){
System.out.println("WebsocketTest..");
}
@OnOpen
public void onopen(Session session){
System.out.println("連接成功");
try {
session.getBasicRemote().sendText("hello client...");
} catch (IOException e) {
e.printStackTrace();
}
}
@OnClose
public void onclose(Session session){
System.out.println("close....");
}
@OnMessage
public void onsend(Session session,String msg){
try {
System.out.println('就是客戶端傳到后台的值'+msg);
Service... service = ContextLoader.getCurrentWebApplicationContext().getBean(service....class);
session.getBasicRemote().sendText(""+傳到HTML網頁上的值);
} catch (IOException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
之前老報這個錯就是調Service層的時候報的:
}
09:34:32.179 [http-bio-8084-exec-9] ERROR o.a.t.w.pojo.PojoEndpointBase - No error handling configured for [jy.websocket.WebsocketTest] and the following error occurred
java.lang.IllegalArgumentException: java.lang.reflect.InvocationTargetException
at org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeBase.onMessage(PojoMessageHandlerWholeBase.java:84)
at org.apache.tomcat.websocket.WsFrameBase.sendMessageText(WsFrameBase.java:369)
at org.apache.tomcat.websocket.WsFrameBase.processDataText(WsFrameBase.java:468)
at org.apache.tomcat.websocket.WsFrameBase.processData(WsFrameBase.java:272)
at org.apache.tomcat.websocket.WsFrameBase.processInputBuffer(WsFrameBase.java:116)
at org.apache.tomcat.websocket.server.WsFrameServer.onDataAvailable(WsFrameServer.java:54)
at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler$WsReadListener.onDataAvailable(WsHttpUpgradeHandler.java:192)
at org.apache.coyote.http11.upgrade.AbstractServletInputStream.onDataAvailable(AbstractServletInputStream.java:178)
at org.apache.coyote.http11.upgrade.AbstractProcessor.upgradeDispatch(AbstractProcessor.java:92)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:601)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException: null
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeBase.onMessage(PojoMessageHandlerWholeBase.java:80)
... 13 common frames omitted
Caused by: java.lang.NullPointerException: null
at jy.websocket.WebsocketTest.onsend(WebsocketTest.java:53)
... 18 common frames omitted
Long.valueOf(msg)3465007
09:34:32.188 [http-bio-8084-exec-9] ERROR o.a.t.w.pojo.PojoEndpointBase - No error handling configured for [jy.websocket.WebsocketTest] and the following error occurred
java.lang.IllegalArgumentException: java.lang.reflect.InvocationTargetException
at org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeBase.onMessage(PojoMessageHandlerWholeBase.java:84)
at org.apache.tomcat.websocket.WsFrameBase.sendMessageText(WsFrameBase.java:369)
at org.apache.tomcat.websocket.WsFrameBase.processDataText(WsFrameBase.java:468)
at org.apache.tomcat.websocket.WsFrameBase.processData(WsFrameBase.java:272)
at org.apache.tomcat.websocket.WsFrameBase.processInputBuffer(WsFrameBase.java:116)
at org.apache.tomcat.websocket.server.WsFrameServer.onDataAvailable(WsFrameServer.java:54)
at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler$WsReadListener.onDataAvailable(WsHttpUpgradeHandler.java:192)
at org.apache.coyote.http11.upgrade.AbstractServletInputStream.onDataAvailable(AbstractServletInputStream.java:178)
at org.apache.coyote.http11.upgrade.AbstractProcessor.upgradeDispatch(AbstractProcessor.java:92)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:601)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException: null
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeBase.onMessage(PojoMessageHandlerWholeBase.java:80)
... 13 common frames omitted
Caused by: java.lang.NullPointerException: null
at jy.websocket.WebsocketTest.onsend(WebsocketTest.java:53)
