【问题标题】:Injecting Spring service in backing bean在支持 bean 中注入 Spring 服务
【发布时间】:2014-02-21 12:54:23
【问题描述】:

我正在尝试使用 netbeans 7.4、SPRING 3.2.3、带有 Primefaces 3.5 和 Glassfish 4.0 的 JSF 2.2 制作网络。

我的目标是创建一个非常简单的项目,在支持 bean 中注入服务。 到目前为止,我已经使用这两个框架在 netbeans 中创建了一个新项目。这些是我项目中的文件:

项目树

webApplication1
  ├ Web Pages
  │    ├ WEB-INF
  │    │    ├ applicationContext.XML
  │    │    ├ dispatcher-servlet.XML
  │    │    ├ faces-config.XML
  │    │    └ web.XML
  │    └ index.XHTML
  ├ source packages
  │    └ controladores
  │         ├ IndexBB.java
  │         ├ Servicio.java
  │         └ ServicioImpl.java
  ├ Test Packages
  ├ Libraries
  ├ Test Libraries
  └ Configuration Files

Index.xhtml

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.org/ui">

    <f:view contentType="text/html">    
        <h:body>
            <h:form>
                <p:inputText id="aInput" value="#{indexBB.mensaje}" />
                <p:commandButton id="btnTest" actionListener="#{indexBB.getServiceSMS}" value="Test" update="aInput" />
            </h:form>            
        </h:body>
    </f:view>
</html>

IndexBB.java

package controladores;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;

@ManagedBean
@ViewScoped
public class IndexBB implements Serializable{

    @ManagedProperty(value="#{rfService}")
    private Servicio elServicio;

    private String mensaje="a default SMS";

    public IndexBB() {

    }

    public String getMensaje() {        
        return this.mensaje;
    }

    public void setMensaje(String mensaje) {
        this.mensaje = mensaje;
    }

    public Servicio getElServicio() {
        return this.elServicio;
    }

    public void setElServicio(Servicio elServicio) {
        this.elServicio = elServicio;
    }

    public void getServiceSMS() {
        this.mensaje=elServicio.getSMS();        
    }
}

Servicio.java

package controladores;

public interface Servicio {

    public String getSMS();
}

ServicioImpl.java

package controladores;

import org.springframework.stereotype.Service;

@Service(value="rfService")
public class ServicioImpl implements Servicio{

    @Override
    public String getSMS() {
    return "a message generated by a service";
    }
}

applicationContext.XML

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"       
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"       
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">


</beans>

dispatcher-servlet.XML

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"    
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"       
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

    <!--
    Most controllers will use the ControllerClassNameHandlerMapping above, but
    for the index controller we are using ParameterizableViewController, so we must
    define an explicit mapping for it.
    -->
    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="index.xhtml">indexController</prop>
            </props>
        </property>
    </bean>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/"
          p:suffix=".xhtml" />

    <!--
    The index controller.
    -->
    <bean name="indexController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="index" />


</beans>

faces-config.XML

<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">

    <application>
        <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
    </application>
</faces-config>

web.XML

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>faces/index.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

如您所见,该项目非常简单。只是一个按钮,它从服务中获取值并将其放入变量中。

问题是当我按下按钮时,Glassfish 给了我一个带有这个 stackTrace 的 NullPointer:

javax.el.ELException: java.lang.NullPointerException
    at com.sun.el.parser.AstValue.invoke(AstValue.java:279)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:149)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:818)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NullPointerException
    at controladores.IndexBB.getServiceSMS(IndexBB.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:275)

在我看来,服务没有被正确注入,所以当我按下按钮时它是 NULL。

我在网上搜索了没有结果(我找到的大部分代码都不起作用)。 有配置 Spring 经验的人可以看看我的项目吗? 提前致谢!

【问题讨论】:

    标签: spring web-services jsf primefaces


    【解决方案1】:

    您有 3 个问题。

    首先,您有一个 DispatcherServlet,它在 JSF 环境中是不需要的。删除它,它的映射。您不需要所有由 JSF 处理的控制器内容。

    其次,你有一个@Service,但没有任何东西在拾取那个 bean。在你的applicationContext.xml 添加组件扫描。

    <context:component-scan base-package="controladores" />
    

    第三,您的托管 bean 有错误的设置器。您必须有一个与 @ManagedProperty 注释中的值匹配的设置器,因此在您的情况下,您应该有一个 setRfService(..) 方法。

    【讨论】:

    • 我删除了 DispatcherServlet,将 "xmlns:context="springframework.org/schema/context" " 和你的行添加到 applicationContext。我也将服务称为“elServicio”,但它仍然不起作用。
    • Stacktrace:加载应用程序时出现异常:java.lang.IllegalStateException:ContainerBase.addChild:开始:org.apache.catalina.LifecycleException:org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException:第 25 行在来自 ServletContext 资源 [/WEB-INF/applicationContext.xml] 的 XML 文档中无效;嵌套异常是 org.xml.sax.SAXParseException;行号:25;列号:60; cvc-complex-type.2.4.c: El comodín 巧合 es estricto, pero no se ha encontrado ninguna declaración para el elemento 'context:component-scan'。
    • ”有问题,有什么想法吗?
    【解决方案2】:

    非常感谢 M. Deinum! 你的答案非常接近,我只需要谷歌一点! 除了您的所有评论之外,我还将这些行添加到“bean”开始标记内的应用程序上下文中:

    xmlns:context="http://www.springframework.org/schema/context" 
    

    xsi:schemaLocation 里面的这个

    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
    

    我还删除了 WEB.XML 中声明调度程序的行:

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    

    还有这个:

    <servlet-mapping>
            <servlet-name>dispatcher</servlet-name>
            <url-pattern>*.xhtml</url-pattern>
        </servlet-mapping>
    

    谢谢!!!

    【讨论】:

      猜你喜欢
      • 2012-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-10
      • 1970-01-01
      • 2012-05-12
      相关资源
      最近更新 更多