在websocket中无法使用spring的注解注入bean对象,可能是实例化时机不一样,具体原因我不请求,有了解的麻烦告我一声.

不止是注入service对象,注入所有对象都得这么弄,还是第一种方法方便点.

第一种,通过ContextLoader获取,直接在上面声明或者方法中获取都可以,

\"\"

private Ops_chatService chat = (Ops_chatService) ContextLoader.getCurrentWebApplicationContext().getBean(\"ops_chatServiceImpl\");

第二种,通过加载spirng配置文件,加载完之后再获取bean,这种性能较差,不建议使用 

ApplicationContext ac = new ClassPath ApplicationContext(\"application. \");
Ops_chatServicee bean = (Ops_chatService)ac.getBean(\"ops_chatServiceImpl\");

 第三种,通过Configurator获取httpsession,通过httpsession可获取service这种比较麻烦点

先写一个继承Configurator的类

 

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;

public class GetHttpSessionConfigurator extends Configurator{
    @Override  
    public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {  
        HttpSession httpSession = (HttpSession) request.getHttpSession();  
        if(httpSession != null){  
            config.getUserProperties().put(HttpSession.class.getName(), httpSession);  
        }  
    }  
}

然后在方法当中获取,其实跟上面那中获取方式一样,只不过通过不同对象获取的applicationcontext 

 @OnOpen  
    public void onOpen(Session session, EndpointConfig config) throws IOException, InterruptedException  {  
        System.out.println(\"Open!\");
        this.session = session;  
        this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());  
        if(httpSession != null){  
            ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(httpSession.getServletContext());  
            Ops_chatServicee Ops_chatServicee = (Ops_chatServicee) ctx.getBean(\"ops_chatServiceImpl\"); 
     
        }  
    }  

由于HTTP协议与websocket协议的不同,导致没法直接从websocket中获取协议,放出去执行,会报空指针值异常,因为这个HttpSession并没有设置进去。而设置HttpSession。需要写一个继承ServletRequestListener的监听器。 

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;

import org.spring work.stereotype.Component;

/**
 * 作用:将所有request请求都携带上httpSession
 * @author zho
 *
 */
@WebListener//配置Listener
@Component
public class RequestListener implements ServletRequestListener {

    public void requestInitialized(ServletRequestEvent sre)  {
        //将所有request请求都携带上httpSession
        ((HttpServletRequest) sre.getServletRequest()).getSession();

    }
    public RequestListener() {
    }

    public void requestDestroyed(ServletRequestEvent arg0)  {
    }
}

收藏 打印