Announcement Announcement Module
Collapse
No announcement yet.
Service not injecting in the Controller Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Service not injecting in the Controller

    Hi to all! I'm new to spring and i find the same problem always i try to do something. The problem is as follows: in my @Controller bean, spring doesn't inject the @Resorce referencing to the @Service, so when i try to load data from service to an UIData component which is in the controller, the ide shows me a NullPointerException.

    I use anotations as you see, and the application is a JSF 2 over Spring 3 and Hibernate 3 too.

    Here's the Stack trace of the error:

    Code:
    org.apache.jasper.el.JspELException: /WEB-INF/jsp/index.jsp(17,12) '#{listarBean.tabla}' Error reading 'tabla' en el tipo paquete.ListarBean
    	at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:107)
    	at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:190)
    	at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:178)
    	at javax.faces.component.UIData.getValue(UIData.java:554)
    	at javax.faces.component.UIData.getDataModel(UIData.java:1248)
    	at javax.faces.component.UIData.setRowIndex(UIData.java:447)
    	at com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:81)
    	at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:823)
    	at javax.faces.component.UIData.encodeBegin(UIData.java:937)
    	at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1611)
    	at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1616)
    	at com.sun.faces.application.view.JspViewHandlingStrategy.doRenderView(JspViewHandlingStrategy.java:420)
    	at com.sun.faces.application.view.JspViewHandlingStrategy.renderView(JspViewHandlingStrategy.java:209)
    	at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:126)
    	at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:127)
    	at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    	at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:313)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    	at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    	at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:859)
    	at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
    	at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1555)
    	at java.lang.Thread.run(Thread.java:662)
    
    Caused by: java.lang.NullPointerException
    	at paquete.ListarBean.getTabla(ListarBean.java:29)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    	at java.lang.reflect.Method.invoke(Method.java:597)
    	at javax.el.BeanELResolver.getValue(BeanELResolver.java:62)
    	at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:54)
    	at com.sun.faces.el.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:72)
    	at org.apache.el.parser.AstValue.getValue(AstValue.java:123)
    	at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:186)
    	at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:101)
    	... 32 more

    And now i'll let you the configuration and the code:

    Here's the applicationContext.xml :

    Code:
    <?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:context="http://www.springframework.org/schema/context"
           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.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
        <context:annotation-config />
        <context:component-scan base-package="paquete" />
    
        <bean id="propertyConfigurer"
              class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
              p:location="/WEB-INF/jdbc.properties" />
        
        <bean id="dataSource"
              class="org.springframework.jdbc.datasource.DriverManagerDataSource"
              p:driverClassName="${jdbc.driverClassName}"
              p:url="${jdbc.url}"
              p:username="${jdbc.username}"
              p:password="${jdbc.password}" />
        
        <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />
            <property name="configLocation" value="classpath:${hibernate.cfg.file}" />
        </bean>
    
    </beans>

    This is the DAO class:


    Code:
    package paquete;
    
    
    import java.util.List;
    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
    import org.springframework.stereotype.Repository;
    
    
    @Repository("hibDao")
    public class HibDao extends HibernateDaoSupport implements HibernateDaoInt
    {
        @Autowired
        public HibDao(SessionFactory sessionFactory)
        {
            super.setSessionFactory(sessionFactory);
        }
    
        public void añadirRegistro(Object obj)
        {
            getHibernateTemplate().saveOrUpdate(obj);
        }
    
        public <T> List<T> obtenerRegistros(Class<T> cls)
        {
            return getHibernateTemplate().loadAll(cls);
        }
    }


    Here's my Service class that use the DAO class defined before:



    Code:
    package paquete;
    
    
    import java.util.List;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    
    @Service("servicioDao")
    public class ServicioDao implements ServicioDaoInt
    {
        private HibernateDaoInt accesoDatos;
    
        @Autowired
        public void setAccesoDatos(HibernateDaoInt accesoDatos){this.accesoDatos=accesoDatos;}
        public HibernateDaoInt getAccesoDatos(){return this.accesoDatos;}
    
    
        public Cursos nuevoCurso(){return new Cursos();}
    
        public void escribirCurso(Cursos curso)
        {
            accesoDatos.añadirRegistro(curso);
        }
    
        public List<Cursos> leerCursos()
        {
            return accesoDatos.obtenerRegistros(Cursos.class);
        }
    }



    The controller one which uses the service defined before:


    Code:
    package paquete;
    
    import java.io.Serializable;
    import javax.faces.component.UIData;
    import javax.faces.model.ListDataModel;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Scope;
    import org.springframework.stereotype.Controller;
    
    
    @Controller("listarBean")
    @Scope("session")
    public class ListarBean implements Serializable
    {
        private ServicioDaoInt servicio;
        
        private UIData tabla;
    
        @Autowired
        public void setServicio(ServicioDaoInt sd){this.servicio=sd;}
        public ServicioDaoInt getServicio(){return this.servicio;}
    
        public String getMensaje(){return this.mensaje;}
        public void setMensaje(String msg){this.mensaje=msg;}
    
        public UIData getTabla()
        {
            this.tabla.setValue(new ListDataModel(this.servicio.leerCursos()));
            return this.tabla;
        }
    
        public void setTabla(UIData tabla)
        {
            this.tabla=tabla;
        }
    }

    Thanks for any help you could offer ^^
    Last edited by CarlosSpring; Jun 29th, 2011, 01:01 PM.

  • #2
    Hola Carlos

    You must read documentation ( a lot really )

    Code:
    org.apache.jasper.el.JspELException: 
    /WEB-INF/jsp/index.jsp(17,12) '#{listarBean.tabla}' 
    Error reading 'tabla' en el tipo Catalogo.ListarBean
    	at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:107)
    Post your JSP code

    Code:
     <context:component-scan base-package="Catalogo" />
    Since when a package name contains uppercase characters?

    Code:
    @Service("servicioDao")
    public class ServicioDao implements ServicioDaoInt
    {
        @Resource(name="hibDao")
        private HibDao accesoDatos;
    
        @Autowired
        public void setAccesoDatos(HibDao ad){this.accesoDatos=ad;}
        public HibDao getAccesoDatos(){return this.accesoDatos;}
    Observations
    1: a DAO must use @Repository, Business classes (BO/Service) use @Service
    2: Is illogical use @Resource and @Autowired both in the same time!, delete @Resource
    3 Be sure HibDao is an interface and not a class, since Spring use Proxy pattern
    4: create setters and getter with the IDE tools, not a hand


    Code:
    @Controller("listarBean")
    @Scope("session")
    public class ListarBean implements Serializable
    {
        @Resource(name="servicioDao")
        private ServicioDao servicio;
        
        private UIData tabla;
    
        @Autowired
        public void setServicio(ServicioDao sd){this.servicio=sd;}
    Again
    1: Is illogical use @Resource and @Autowired both in the same time!, delete @Resource
    3 You must use the interface used for ServicioDao and not use the class name directly, since Spring use Proxy pattern
    3: create setters and getter with the IDE tools, not a hand

    Seems You are doing a wrong integration about Spring MVC + JSF

    @Controller("listarBean") is used for URL resolution and you are using to access your backed bean
    Code:
    org.apache.jasper.el.JspELException: /WEB-INF/jsp/index.jsp(17,12) '#{listarBean.tabla}'
    I suggest you read more about how do this integration

    Comment


    • #3
      Hi dr_pompeii! Thank for your advices, i know i must have had a lot of errors, even problems with concept, but i don't have more time to learn slowly for this time, i have to present a program this friday to demonstrate i can integrate jsf, spring and hibernate, and spring is giving me a lot of problems as you can see xD, although after i've done and showed this program i'll do, i promise ^^

      I've changed the things you've said to me and i edited my first post to show this changes. I only put in this one the things i can't put in the other (i exceed the 10,000 characters).

      Now the package "Catalogo" is called "paquete" (the name change is because i had problems with capitalization between "Catalogo" and "catalogo")

      I've removed all @Resource annotations and let only the @Autowired ones.

      Now i use an interface for the DAO and other for the Service.


      This is the jsp file which uses the controller:

      Code:
      <%@page contentType="text/html" pageEncoding="UTF-8"%>
      <%@taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
      <%@taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
         "http://www.w3.org/TR/html4/loose.dtd">
      
      <html>
          <head>
              <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
              <title>Catalogo</title>
          </head>
      
          <body>
              <f:view>
                  <h:outputText value="#{listarBean.mensaje}" />
                  
                  <h:dataTable value="#{listarBean.tabla}" rows="5" border="2" var="t" >
                      <h:column>
                          <f:facet name="header">
                              <h:outputText value="Titulo" />
                          </f:facet>
                          
                          <h:outputText value="#{t.titulo}" />
                      </h:column>
      
                      <h:column>
                          <f:facet name="header">
                              <h:outputText value="Nivel" />
                          </f:facet>
      
                          <h:outputText value="#{t.nivel}" />
                      </h:column>
      
                      <h:column>
                          <f:facet name="header">
                              <h:outputText value="Horas" />
                          </f:facet>
      
                          <h:outputText value="#{t.horas}" />
                      </h:column>
      
                      <h:column>
                          <f:facet name="header">
                              <h:outputText value="Profesor" />
                          </f:facet>
      
                          <h:outputText value="#{t.profesor}" />
                      </h:column>
      
                      <h:column>
                          <f:facet name="header">
                              <h:outputText value="Activo" />
                          </f:facet>
      
                          <h:outputText value="#{t.activo}" />
                      </h:column>
                  </h:dataTable>
              </f:view>
          </body>
      </html>

      Initially i was accesing my backed bean using the class name, i mean, #{ListarBean.tabla}, and i put things like @Controller only, not @Controller("listarBean"), and the same for @Service and the others, but it didn't work so i tried to use my own names because it could be a problem with spring auto generated names for beans. It worked fine.

      In fact i've defined String variable with a fixxed value in the controller, and i can show its value in the jsp using #{listarBean.variable}. Anyways, i can change it if you advice this to me.

      I think the problem is in spring, exactly in this method :

      Code:
      public UIData getTabla()
          {
              this.tabla.setValue(new ListDataModel(this.servicio.leerCursos()));
              return this.tabla;
          }
      in the reference to servicio.leerCursos() method because servicio is a null reference and because the compiler is telling me where the problem starts:

      Code:
      Caused by: java.lang.NullPointerException
      	at paquete.ListarBean.getTabla(ListarBean.java:29)
      Last edited by CarlosSpring; Jun 29th, 2011, 05:00 PM.

      Comment


      • #4
        I have one question, my class ServicioDao must be serializable? ListarBean is Serializable and his attribute of type Servicio must be too to get this capability, but this means that i'll have to make HibDao class Serializable too for the same reason, ServicioDao has an attribute of type HibDao (the interface HibDaoInt, not the class implementing it), and over and over again, so it's a bit confusing, isn't it? Anyways, in others examples i've seen no-one defines theese classes as Serializable but the bean one, so i didn't.
        Last edited by CarlosSpring; Jun 29th, 2011, 04:57 PM.

        Comment


        • #5
          Hi! i have gone on trying and reading to solve this, and i've found this error in the Apache log:

          Code:
          30-jun-2011 13:16:05 org.apache.catalina.session.StandardSession writeObject
          ADVERTENCIA: No puedo serializar atributo de sesión listarBean para sesión 82A791064D24733FC0476E7AB704FCA9
          java.io.NotSerializableException: paquete.ServicioDao
                  at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1164)
                  at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1518)
                  at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1483)
                  at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400)
                  at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158)
                  at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:330)
                  at org.apache.catalina.session.StandardSession.writeObject(StandardSession.java:1546)
                  at org.apache.catalina.session.StandardSession.writeObjectData(StandardSession.java:989)
                  at org.apache.catalina.session.StandardManager.doUnload(StandardManager.java:517)
                  at org.apache.catalina.session.StandardManager.unload(StandardManager.java:463)
                  at org.apache.catalina.session.StandardManager.stop(StandardManager.java:667)
                  at org.apache.catalina.core.StandardContext.stop(StandardContext.java:4611)
                  at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3222)
                  at org.apache.catalina.manager.ManagerServlet.reload(ManagerServlet.java:943)
                  at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:361)
                  at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
                  at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
                  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
                  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
                  at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:199)
                  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
                  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
                  at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
                  at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
                  at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:558)
                  at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
                  at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
                  at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
                  at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
                  at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:859)
                  at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
                  at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1555)
                  at java.lang.Thread.run(Thread.java:662)
          I've read this happens because i'm using a non serializable object in a persistent session, and that i can ignore it beacuse this is happening when it tries to write to a file session information, but doesn't affect to my program and doesn't cause the null pointer fail.
          Last edited by CarlosSpring; Jun 30th, 2011, 07:33 AM.

          Comment


          • #6
            I've tried another way, following the spring manual and the intergrating with other web frameworks section. So instead of using the @Controller annotation, i changed it by a @ManagedBean one (as i was definig between <managed-bean> tag in faces-config.xml), using @ManagedProperty(value="#{servicioDao}") (the varaible servicio now is called servicioDao, as the object that represents but without the first capital character) for the service object. Have i to let the setter with @Autowired annotation or must i remove it? Anyways, i still get the same null pointer exception.
            Last edited by CarlosSpring; Jun 30th, 2011, 10:30 AM.

            Comment


            • #7
              I've solved the problem. Finally, what failed was the UIData component, which wasn't initialized, and not the bean. A stupid fail xD

              Anyways, thanks for your help.

              Comment

              Working...
              X