Announcement Announcement Module
Collapse
No announcement yet.
Why Am I Getting A Null Pointer Exception Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Why Am I Getting A Null Pointer Exception

    Im using spring and neo4j to make an application that stores peoples information in a database. Every time I launch my application im getting this error but cant figure out why. My code is below the error.

    Code:
    HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException
    
    type Exception report
    
    message Request processing failed; nested exception is java.lang.NullPointerException
    
    description The server encountered an internal error that prevented it from fulfilling this request.
    
    exception
    
    org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    	org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
    	org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    	org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    	org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    	org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    	org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    root cause
    
    java.lang.NullPointerException
    	com.mycompany.smsdatabase.service.PersonImport.doImportPerson(PersonImport.java:30)
    	com.mycompany.smsdatabase.controller.HomeController.Home(HomeController.java:24)
    	sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    	sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	java.lang.reflect.Method.invoke(Method.java:601)
    	org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    	org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
    	org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
    	org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
    	org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
    	org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
    	org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    	org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    	org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    	org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    	org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    note The full stack trace of the root cause is available in the Apache Tomcat/7.0.40 logs.
    Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package com.mycompany.smsdatabase.controller;
    
    import com.mycompany.smsdatabase.domain.Person;
    import com.mycompany.smsdatabase.service.PersonImport;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    /**
     *
     * @author Anthony
     */
    @Controller
    public class HomeController {
       
        @RequestMapping(value = "/", method = RequestMethod.GET)
        public String Home()
        {
           PersonImport person = new PersonImport();
           person.doImportPerson("anthony");
          return "index";
        }
    }
    Code:
     */
    package com.mycompany.smsdatabase.service;
    import com.mycompany.smsdatabase.domain.Person;
    import com.mycompany.smsdatabase.repositories.PersonRepository;
    import javax.transaction.Transaction;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    /**
     *
     * @author Anthony
     */
    @Service
    public class PersonImport {
        @Autowired
       private PersonRepository PersonRepository;
     
     public Person doImportPerson(String id)
     {   
         Person person = PersonRepository.findById(id);
         if (person == null) {
               person = new Person(id,null);
           }
         PersonRepository.save(person);
         System.out.println("+++++++++++++++++++++++++++++++++++++hello+++++++++++++");
         return person;
     }
    }
    Code:
    import com.mycompany.smsdatabase.domain.Person;
    import org.springframework.data.neo4j.core.GraphDatabase;
    import org.springframework.data.neo4j.repository.GraphRepository;
    
    /**
     *
     * @author Anthony
     */
    public interface PersonRepository extends GraphRepository<Person>{
        Person findById(String id);
    }

  • #2
    Your controller directly instanciates PersonImport, so there's no dependency injection happening, which is why the repository isn't wired (which is where I assume the NPE is happening). Autowire the PersonImport bean in the controller and it should work.

    Comment


    • #3
      Originally posted by Johannes Mockenhaupt View Post
      Your controller directly instanciates PersonImport, so there's no dependency injection happening, which is why the repository isn't wired (which is where I assume the NPE is happening). Autowire the PersonImport bean in the controller and it should work.
      When i autowire PersonImport i am getting this error

      Code:
      SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
      org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.mycompany.smsdatabase.service.PersonImport com.mycompany.smsdatabase.controller.HomeController.personImport; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.mycompany.smsdatabase.service.PersonImport] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
      	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
      	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
      	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
      	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
      	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
      	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
      	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
      	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
      	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
      	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
      	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
      	at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:384)
      	at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
      	at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
      	at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4887)
      	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5381)
      	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
      	at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3926)
      	at org.apache.catalina.manager.ManagerServlet.reload(ManagerServlet.java:954)
      	at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:364)
      	at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
      	at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
      	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
      	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
      	at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
      	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
      	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
      	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
      	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
      	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:581)
      	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
      	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
      	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
      	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
      	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
      	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1008)
      	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
      	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
      	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
      	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
      	at java.lang.Thread.run(Thread.java:722)
      Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.mycompany.smsdatabase.service.PersonImport com.mycompany.smsdatabase.controller.HomeController.personImport; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.mycompany.smsdatabase.service.PersonImport] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
      	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
      	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
      	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
      	... 40 more
      Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.mycompany.smsdatabase.service.PersonImport] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
      	at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:924)
      	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793)
      	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
      	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
      	... 42 more

      Comment


      • #4
        what does your spring config look like?

        Comment


        • #5
          Originally posted by MichaelHunger View Post
          what does your spring config look like?
          my applicationContext looks like this
          Code:
          <?xml version="1.0" encoding="UTF-8" standalone="no"?>
          <beans xmlns="http://www.springframework.org/schema/beans"
                 xmlns:context="http://www.springframework.org/schema/context"
                 xmlns:mvc="http://www.springframework.org/schema/mvc" 
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
                 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/context 
              http://www.springframework.org/schema/context/spring-context-3.0.xsd
              http://www.springframework.org/schema/mvc
              http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
              http://www.springframework.org/schema/data/neo4j
              http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd 
              http://www.springframework.org/schema/tx 
              http://www.springframework.org/schema/tx/spring-tx.xsd">
              
            <context:annotation-config/>
              <context:component-scan base-package="com.mycompany.smsdatabase">
                  <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
              </context:component-scan>
              
              <context:spring-configured/>
              
              <bean 
          class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
              
              <neo4j:config storeDirectory="target/data/graph.db"/>
              <neo4j:repositories base-package="com.mycompany.smsdatabase.repositories"/>
              
              <bean id="graphDatabaseService" class="org.neo4j.test.ImpermanentGraphDatabase" destroy-method="shutdown"/>
              <tx:annotation-driven mode="proxy"/>
          </beans>
          my Dispatch servlet looks like this

          Code:
          <beans xmlns="http://www.springframework.org/schema/beans"
          	xmlns:context="http://www.springframework.org/schema/context"
          	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          	xsi:schemaLocation="
                  http://www.springframework.org/schema/beans     
                  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                  http://www.springframework.org/schema/context 
                  http://www.springframework.org/schema/context/spring-context-3.0.xsd">
           
          	<context:component-scan base-package="com.mycompany.smsdatabase" />
           
          	<bean
          		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
          		<property name="prefix">
          			<value>/WEB-INF/</value>
          		</property>
          		<property name="suffix">
          			<value>.jsp</value>
          		</property>
          	</bean>
           
          </beans>
          my web xml looks like

          Code:
          <?xml version="1.0" encoding="UTF-8"?>
          
          <web-app xmlns="http://java.sun.com/xml/ns/javaee"
          	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          	 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
          	 version="3.0">
              
              <context-param>
              	<param-name>contextClass</param-name>
              	<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
          	</context-param>
          
          	<!-- Location of Java @Configuration classes that configure the components that makeup this application -->
          	<context-param>
              	<param-name>contextConfigLocation</param-name>
              	<param-value>com.mycompany.smsdatabase.controller
                               /WEB-INF/applicationContext.xml
                  </param-value>
          	</context-param>
                  
          	
          	<!-- Creates the Spring Container shared by all Servlets and Filters -->
          	<listener>
          		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
          	</listener>
          
          	<!-- Ensure UTF-8 character encoding is used -->
          	<filter>
          		<filter-name>encodingFilter</filter-name>
          		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
          		<init-param>
          			<param-name>encoding</param-name>
          			<param-value>UTF-8</param-value>
          		</init-param>
          		<init-param>
          			<param-name>forceEncoding</param-name>
          			<param-value>true</param-value>
          		</init-param>
          	</filter>
          
          	<filter-mapping>
          		<filter-name>encodingFilter</filter-name>
          		<url-pattern>/*</url-pattern>
          	</filter-mapping>
          
          	<!-- Enables support for DELETE and PUT request methods with web browser clients -->
          	<filter>
          		<filter-name>hiddenHttpMethodFilter</filter-name>
          		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
          	</filter>
          
          	<filter-mapping>
          		<filter-name>hiddenHttpMethodFilter</filter-name>
          		<url-pattern>/*</url-pattern>
          	</filter-mapping>
          
          	<servlet>
          		<servlet-name>appServlet</servlet-name>
          		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
          		<init-param>
          			<param-name>contextConfigLocation</param-name>
          			<param-value>/WEB-INF/dispatcherServlet.xml</param-value>
          		</init-param>
          		<load-on-startup>1</load-on-startup>
          	</servlet>
          
          	<servlet-mapping>
          		<servlet-name>appServlet</servlet-name>
          		<url-pattern>/</url-pattern>
          	</servlet-mapping>
                  
          <servlet>
          		<servlet-name>H2Console</servlet-name>
          		<servlet-class>org.h2.server.web.WebServlet</servlet-class>
          		<init-param>
          			<param-name>-webAllowOthers</param-name>
          			<param-value>true</param-value>
          		</init-param>
          		<load-on-startup>2</load-on-startup>
          	</servlet>
          
          	<servlet-mapping>
          		<servlet-name>H2Console</servlet-name>
          		<url-pattern>/admin/h2/*</url-pattern>
          	</servlet-mapping>
                  
              <session-config>
                  <session-timeout>
                      30
                  </session-timeout>
              </session-config>
          </web-app>

          Comment


          • #6
            Originally posted by IceNine View Post
            my web xml looks like

            Code:
            <?xml version="1.0" encoding="UTF-8"?>
            
            <web-app xmlns="http://java.sun.com/xml/ns/javaee"
            	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            	 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
            	 version="3.0">
                
                <context-param>
                	<param-name>contextClass</param-name>
                	<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
            	</context-param>
            
            	<!-- Location of Java @Configuration classes that configure the components that makeup this application -->
            	<context-param>
                	<param-name>contextConfigLocation</param-name>
                	<param-value>com.mycompany.smsdatabase.controller
                                 /WEB-INF/applicationContext.xml
                    </param-value>
            	</context-param>
                    ...
            The param-value of context-param looks broken to me ... it's been a while since I configured spring using xml, but shouldn't that just be a path?

            Comment


            • #7
              Shouldn't you exclude the non-controllers in the dispatch-servlet component scan?

              Comment


              • #8
                You are constructing yuor own instance of classes where as you should be using the spring configured ones (i.e. autowired).

                Code:
                @Controller
                public class HomeController {
                   
                    @RequestMapping(value = "/", method = RequestMethod.GET)
                    public String Home()
                    {
                       PersonImport person = new PersonImport();
                       person.doImportPerson("anthony");
                      return "index";
                    }
                }
                next to that your configuration is wrong/flawed as you are duplicating bean instances...

                applicationcontext
                Code:
                <context:component-scan base-package="com.mycompany.smsdatabase">
                dispatcherservlet
                Code:
                <context:component-scan base-package="com.mycompany.smsdatabase">
                Both are scanning the same path and detecting and instantiating the same beans (at least your services). You should configure the one in your dispatcher servlet to only scan for @Controller (basically the reverseof the one in your applicationcontxt and including the disabling of the default filters!)

                Code:
                <context:component-scan base-package="com.mycompany.smsdatabase" use-default-filters="false">
                        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
                    </context:component-scan>
                Also you have way to much in your applicationcontext.xml
                Code:
                 <context:annotation-config/>
                    <context:component-scan base-package="com.mycompany.smsdatabase">
                        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
                    </context:component-scan>
                    
                    <context:spring-configured/>
                    
                    <bean 
                class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
                The red is already implied by the compont-scan element. The blue part is only needed if you use spring and have it autowire beans outside of its scope (i.e. using @Configurable).

                Also whu in yuour web.xml you are configuring the xml and component path in your contextConfigLocation? Basically you have duplicated all the beans now.

                Code:
                <context-param>
                    	<param-name>contextClass</param-name>
                    	<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
                	</context-param>
                
                	<!-- Location of Java @Configuration classes that configure the components that makeup this application -->
                	<context-param>
                    	<param-name>contextConfigLocation</param-name>
                    	<param-value>com.mycompany.smsdatabase.controller
                                     /WEB-INF/applicationContext.xml
                        </param-value>
                	</context-param>
                Remove the path and you can then also remove the contextClass parameter (as you are still using xml and not java based configuration).
                Last edited by Marten Deinum; Aug 14th, 2013, 03:32 AM.

                Comment

                Working...
                X