Tomcat 中的 WebSocket <o:socket> NoSuchBeanDefinitionException

WebSocket <o:socket> NoSuchBeanDefinitionException in Tomcat

我尝试在 omnifaces 中重新创建演示示例 https://showcase.omnifaces.org/push/socket

Tomcat 使用以下堆栈跟踪抛出 NoSuchBeanDefinitionException

28-Dec-2021 17:29:41.969 SEVERE [http-nio-8080-exec-1] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [default] in context with path [/ms-app] threw exception [Error creating bean with name 'alertUsers': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.ms.webapp.action.alertUsers.setPush(org.omnifaces.cdi.PushContext); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.omnifaces.cdi.PushContext] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}] with root cause
    org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.omnifaces.cdi.PushContext] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
            at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1103)
            at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:963)
            at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
            at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:553)
            at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
            at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
            at org.springframework.beans.factory.support.AbstractBeanFactory.getObject(AbstractBeanFactory.java:304)
            at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
            at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
            at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
            at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
            at org.springframework.beans.factory.access.el.SpringBeanELResolver.getValue(SpringBeanELResolver.java:55)
            at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:180)
            at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:208)
            at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:94)
            at org.apache.el.parser.AstValue.getValue(AstValue.java:137)
            at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:190)
            at org.jboss.weld.module.web.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
            at com.sun.faces.facelets.el.ELText$ELTextVariable.writeText(ELText.java:258)
            at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:86)
            at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:83)
            at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:307)
            at com.sun.faces.renderkit.html_basic.GroupRenderer.encodeChildren(GroupRenderer.java:114)
            at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:918)
            at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1905)
            at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1908)
            at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1908)
            at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:491)
            at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:194)
            at com.ocpsoft.pretty.faces.application.PrettyViewHandler.renderView(PrettyViewHandler.java:163)
            at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:151)
            at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:151)
            at org.omnifaces.viewhandler.OmniViewHandler.renderView(OmniViewHandler.java:115)
            at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:126)
            at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
            at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:223)
            at javax.faces.webapp.FacesServlet.service(FacesServlet.java:671)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
            at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:89)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
            at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
            at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:145)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
            at com.ms.webapp.filter.MessageFilter.doFilter(MessageFilter.java:44)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
            at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
            at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
            at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
            at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
            at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
            at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:139)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
            at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
            at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
            at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
            at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
            at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
            at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
            at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
            at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
            at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
            at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
            at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
            at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
            at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:145)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
            at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:713)
            at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:462)
            at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:387)
            at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:315)
            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:498)
            at net.bull.javamelody.JspWrapper.invoke(JspWrapper.java:150)
            at net.bull.javamelody.JdbcWrapper$DelegatingInvocationHandler.invoke(JdbcWrapper.java:286)
            at com.sun.proxy.$Proxy207.forward(Unknown Source)
            at org.tuckey.web.filters.urlrewrite.NormalRewrittenUrl.doRewrite(NormalRewrittenUrl.java:195)
            at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:159)
            at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:141)
            at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:90)
            at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:417)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
            at com.ms.webapp.filter.LocaleFilter.doFilterInternal(LocaleFilter.java:67)
            at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
            at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
            at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
            at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:201)
            at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:178)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
            at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
            at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
            at org.apache.catalina.valves.rewrite.RewriteValve.invoke(RewriteValve.java:305)
            at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
            at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
            at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:615)
            at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
            at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:818)
            at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1626)
            at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
            at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
            at java.lang.Thread.run(Thread.java:748)

我已经在 Tomcat 中使用 balusC 教程安装了 Weld https://balusc.omnifaces.org/2013/10/how-to-install-cdi-in-tomcat.html

xhtml 片段

<h3>Global counter</h3>
<p>
    Below is a static counter which has the same value application wide.
</p>

<h1><h:panelGroup id="count">#{alertUsers.count}</h:panelGroup></h1>

<h:form>
    <p>
        If you enable the push, then a websocket will be opened.
        Note that it's by default always auto-connected when included in the page, but for demo purposes we're initially disabling it.
    </p>
    <p>
        <h:panelGroup id="toggle">
            Push is #{alertUsers.connected ? 'connected' : 'disconnected'} 
            <h:commandButton value="#{alertUsers.connected ? 'disconnect' : 'connect'} it" action="#{alertUsers.toggle}">
                <f:ajax render="toggle increment :count"/>
            </h:commandButton>
        </h:panelGroup>
    </p>
    <p>
        If push is connected and you press the "increment!" button, then the static counter will increment in bean and the push will send out the new value to the same channel in all connected clients.
        To see it yourself, open the same page in multiple tabs/windows/browsers/machines and trigger the push in only one of it.
        Note that the counter also won't increment from other side if push is still disconnected on current page.
    </p>
    <p>
        <h:commandButton id="increment" value="increment!" action="#{alertUsers.increment}" disabled="#{not alertUsers.connected}">
            <f:ajax />
        </h:commandButton>
    </p>
</h:form>


<!-- NOTE: having inline script in XHTML like below is bad practice. -->
<!-- It's included directly in XHTML just for sake of demo. -->
<!-- In real world code, put it in a JS file :) -->

<script>
    function updateCounter(newvalue) {
        $("#count").text(newvalue);
    }

    function onclosePush(code) {
        if (code == -1) {
            alert("Oops! Your browser doesn't seem to support web sockets. The push functionality won't work.")
        }
        else if (code != 1000) {
            alert("Oops! Push has stopped working with error code " + code + "! Reload the page.")
        }
    }
</script>

<!-- End of bad practice ;) -->


<o:socket channel="counter" onmessage="updateCounter" onclose="onclosePush" connected="#{alertUsers.connected}" />

alertUsers.java

import java.io.Serializable;
import java.util.concurrent.atomic.AtomicLong;

import javax.inject.Inject;
import javax.inject.Named;

import org.omnifaces.cdi.Push;
import org.omnifaces.cdi.PushContext;
import org.omnifaces.cdi.ViewScoped;

@Named("alertUsers")
@ViewScoped
public class alertUsers implements Serializable {

    private static AtomicLong counter = new AtomicLong();

    private boolean connected;

    @Inject @Push(channel="counter")
    private PushContext push;

    public void toggle() {
        connected = !connected;
    }

    public void increment() {
        long newvalue = counter.incrementAndGet();
        push.send(newvalue);
    }

    public boolean isConnected() {
        return connected;
    }

    public Long getCount() {
        return counter.get();
    }

}

Maven-spring 可以很好地编译它,但是当我将 jar 放入 WEB/lib 时,Tomcat localhost 会抛出上述异常。 我目前的猜测是我不能在 omnifaces.cdi.PushContext 中使用 Inject。我需要专门定义bean吗?怎么样?

顺便说一句,如果我使用 com.google.inject.Inject 而不是 javax.inject.Inject,Tomcat 不会抛出上述错误,但计数器不会自动更新并且连接会使用 onclosePush 关闭函数和 1008 错误代码。

万一有人需要这个。我决定放弃 Omnifaces-Spring 因为它与其他人建议的不兼容。参见