title: Spring MVC3.2.2 + Hibernate4 + @Autowire SessionFactory sessionFactory gives nullpointer exception
body: <p>I am using GenricHibernateDAO which autowires a sessionfactory, which getting set to null all the time when I call the save(user) method through controller, it give me a null pointer exception.</p>
  
  <pre><code>package com.hdo.dao;
      public class GenericHibernateDAO&lt;T&gt; implements GenericDAO&lt;T&gt; {
  
          @Autowired
          private SessionFactory sessionFactory;
  
          public void setSessionFactory(SessionFactory sessionFactory) {
              this.sessionFactory = sessionFactory;
          }
  
  
          @Override
          @Transactional
          public void save(T t) {
              // TODO Auto-generated method stub
              sessionFactory.getCurrentSession().save(t);
          }
      }
  </code></pre>
  
  <p>UserDAO :</p>
  
  <pre><code>@Repository
  public class UserDAO extends GenericHibernateDAO&lt;User&gt; {
  
      public UserDAO() {
          super(User.class);
      }
      public void createUser(User user) {
  
          save(user);
      }
  }
  </code></pre>
  
  <p>Controller :</p>
  
  <pre><code>@Controller
  public class BasicController {
  
      Logger _LOG = Logger.getLogger(BasicController.class);
  
      @RequestMapping("/")
      public ModelAndView home() {
          return new ModelAndView("index");
      }
  
      @RequestMapping("/userHome")
      public ModelAndView goHome(@ModelAttribute("user") User user, Map&lt;String, Object&gt; map, HttpServletRequest request) {
          if (null != user) {
              //userForm.get
              int noOfBreeds = Integer.parseInt(user.getNoOfBreeds());
              for (int i = 0; i &lt; noOfBreeds; i++) {
                  Pet pet = new Pet();
                  String dogName = request.getParameter("dogName"+i);
                  String breed = request.getParameter("breed"+i);
                  pet.setPetName(dogName);
                  pet.setPetType(breed);
  
                  user.addPet(pet);
              }
  
              new UserDAO().save(user);
          }
  
          return new ModelAndView("userHome");
      }
  }
  </code></pre>
  
  <p>pom.xml (properties)</p>
  
  <pre><code>spring.version : 3.2.2.RELEASE
  jdk.version : 1.7
  hibernate.version : 4.2.0.Final
  mysql.connector.version : 5.1.21 
  tomcat.version : 7.0.33
  cglib : 2.2.2
  jstl : 1.2
  commons-dbcp : 1.4
  javax.servlet : 3.0.1
  </code></pre>
  
  <p>spring-servlet.xml</p>
  
  <pre><code>&lt;beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:tx="http://www.springframework.org/schema/tx"
         xmlns:mvc="http://www.springframework.org/schema/mvc"
         xmlns:context="http://www.springframework.org/schema/context"
  
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
              http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
              http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"&gt;        
  
      &lt;context:component-scan base-package="com.hdo" /&gt;
      &lt;mvc:annotation-driven /&gt;
  
      &lt;bean id="messageSource"
          class="org.springframework.context.support.ReloadableResourceBundleMessageSource"&gt;
          &lt;property name="basename" value="classpath:i18n/messages" /&gt;
          &lt;property name="defaultEncoding" value="UTF-8" /&gt;
      &lt;/bean&gt;
  
      &lt;bean id="localeChangeInterceptor"
          class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"&gt;
          &lt;property name="paramName" value="lang" /&gt;
      &lt;/bean&gt;
  
      &lt;bean id="localeResolver"
          class="org.springframework.web.servlet.i18n.CookieLocaleResolver"&gt;
          &lt;property name="defaultLocale" value="en" /&gt;
      &lt;/bean&gt;
  
      &lt;bean
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt;
          &lt;property name="prefix" value="/WEB-INF/views/" /&gt;
          &lt;property name="suffix" value=".jsp" /&gt;
      &lt;/bean&gt;
  
  &lt;/beans&gt;
  </code></pre>
  
  <p>application-context.xml </p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:tx="http://www.springframework.org/schema/tx"
         xmlns:mvc="http://www.springframework.org/schema/mvc"
         xmlns:context="http://www.springframework.org/schema/context"
  
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
              http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
              http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"&gt;
  
      &lt;context:annotation-config&gt;&lt;/context:annotation-config&gt;
  &lt;context:property-placeholder location="classpath:jdbc.properties"/&gt;
  
  &lt;bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;
      &lt;property name="driverClassName"&gt;
          &lt;value&gt;${jdbc.driverClassName}&lt;/value&gt;
      &lt;/property&gt;
      &lt;property name="url"&gt;
          &lt;value&gt;${jdbc.databaseurl}&lt;/value&gt;
      &lt;/property&gt;
      &lt;property name="username"&gt;
          &lt;value&gt;${jdbc.username}&lt;/value&gt;
      &lt;/property&gt;
      &lt;property name="password"&gt;
          &lt;value&gt;${jdbc.password}&lt;/value&gt;
      &lt;/property&gt;
  &lt;/bean&gt;
  
      &lt;bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt;
          &lt;property name="dataSource" ref="dataSource" /&gt;
          &lt;property name="packagesToScan" value="com.hdo.model" /&gt; &lt;!-- assuming that is the package with your hibernate entities --&gt;
          &lt;property name="hibernateProperties"&gt;
              &lt;props&gt;
                  &lt;prop key="hibernate.dialect"&gt;${jdbc.dialect}&lt;/prop&gt;
                  &lt;prop key="hibernate.show_sql"&gt;${jdbc.showSql}&lt;/prop&gt;
              &lt;/props&gt;
          &lt;/property&gt;
      &lt;/bean&gt;
  
      &lt;tx:annotation-driven transaction-manager="transactionManager"/&gt;
  
      &lt;bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"&gt;
          &lt;property name="sessionFactory" ref="sessionFactory"/&gt;
      &lt;/bean&gt;
  
  &lt;/beans&gt;
  </code></pre>
  
  <p>Web.xml :</p>
  
  <pre><code>    &lt;context-param&gt;
              &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
              &lt;param-value&gt;/WEB-INF/application-context.xml, /WEB-INF/spring-servlet.xml&lt;/param-value&gt;
   &lt;/context-param&gt;
  
  &lt;listener&gt;
       &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
  &lt;/listener&gt;
  
  &lt;servlet&gt;
      &lt;servlet-name&gt;spring&lt;/servlet-name&gt;
      &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
      &lt;init-param&gt;
          &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
          &lt;param-value&gt;&lt;/param-value&gt;
      &lt;/init-param&gt;
      &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
  &lt;/servlet&gt;
  
  &lt;servlet-mapping&gt;
      &lt;servlet-name&gt;spring&lt;/servlet-name&gt;
      &lt;url-pattern&gt;*.do&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
  </code></pre>
  
  <p>Logs are here :</p>
  
  <pre><code>    00:06:06,297 DEBUG DefaultIdentifierGeneratorFactory:93 - Registering IdentifierGenerator strategy [enhanced-table] -&gt; [org.hibernate.id.enhanced.TableGenerator]
      00:06:06,304  INFO Configuration:1969 - HHH000044: Configuring from URL: file:/home/hanu/tools/tomcat7maven_hpo/webapps/hpo/WEB-INF/classes/hibernate.cfg.xml
      00:06:06,357 DEBUG DTDEntityResolver:68 - Trying to resolve system-id [http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd]
      00:06:06,365 DEBUG DTDEntityResolver:70 - Recognized hibernate namespace; attempting to resolve on classpath under org/hibernate/
      00:06:06,367 DEBUG DTDEntityResolver:107 - Located [http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd] in classpath
      00:06:06,400 DEBUG Configuration:2134 - Session-factory config [null] named class [com.hdo.model.User] for mapping
      00:06:06,417  INFO Configuration:2074 - HHH000041: Configured SessionFactory: null
  
  
      00:06:06,715 DEBUG SimpleValueBinder:331 - building SimpleValue for userName
      00:06:06,716 DEBUG PropertyBinder:260 - Building property userName
      00:06:06,719 DEBUG SimpleValueBinder:369 - Setting SimpleValue typeName for id
      00:06:06,720 DEBUG SimpleValueBinder:369 - Setting SimpleValue typeName for confirmPassword
      00:06:06,720 DEBUG SimpleValueBinder:369 - Setting SimpleValue typeName for country
      00:06:06,720 DEBUG SimpleValueBinder:369 - Setting SimpleValue typeName for email
      00:06:06,721 DEBUG SimpleValueBinder:369 - Setting SimpleValue typeName for location
      00:06:06,721 DEBUG SimpleValueBinder:369 - Setting SimpleValue typeName for noOfBreeds
      00:06:06,722 DEBUG SimpleValueBinder:369 - Setting SimpleValue typeName for password
      00:06:06,722 DEBUG SimpleValueBinder:369 - Setting SimpleValue typeName for postCode
      00:06:06,723 DEBUG SimpleValueBinder:369 - Setting SimpleValue typeName for state
      00:06:06,723 DEBUG SimpleValueBinder:369 - Setting SimpleValue typeName for userName
      00:06:06,725 DEBUG Configuration:1406 - Processing fk mappings (*ToOne and JoinedSubclass)
      00:06:06,728 DEBUG Configuration:1585 - Processing extends queue
      00:06:06,729 DEBUG Configuration:1643 - Processing extends queue
      00:06:06,729 DEBUG Configuration:1588 - Processing collection mappings
      00:06:06,730 DEBUG Configuration:1598 - Processing native query and ResultSetMapping mappings
      00:06:06,730 DEBUG Configuration:1606 - Processing association property references
      00:06:06,730 DEBUG Configuration:1628 - Creating tables' unique integer identifiers
      00:06:06,731 DEBUG Configuration:1629 - Processing foreign key constraints
      00:06:07,128 DEBUG JdbcServicesImpl:121 - Database -&gt;
         name : MySQL
      version : 5.5.29-0ubuntu0.12.10.1
        major : 5
        minor : 5
      00:06:07,129 DEBUG JdbcServicesImpl:127 - Driver -&gt;
         name : MySQL-AB JDBC Driver
      version : mysql-connector-java-5.1.21 ( Revision: ${bzr.revision-id} )
        major : 5
        minor : 1
      00:06:07,130 DEBUG JdbcServicesImpl:133 - JDBC version : 4.0
      00:06:07,169  INFO Dialect:128 - HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
      00:06:07,216 DEBUG SettingsFactory:114 - Automatic flush during beforeCompletion(): disabled
      00:06:07,217 DEBUG SettingsFactory:120 - Automatic session close at end of transaction: disabled
      00:06:07,217 DEBUG SettingsFactory:131 - JDBC batch size: 15
      00:06:07,218 DEBUG SettingsFactory:137 - JDBC batch updates for versioned data: disabled
      00:06:07,218 DEBUG SettingsFactory:147 - Scrollable result sets: enabled
      00:06:07,219 DEBUG SettingsFactory:153 - Wrap result sets: disabled
      00:06:07,219 DEBUG SettingsFactory:159 - JDBC3 getGeneratedKeys(): enabled
      00:06:07,219 DEBUG SettingsFactory:171 - multi-tenancy strategy : NONE
      00:06:07,220 DEBUG SettingsFactory:177 - Connection release mode: auto
      00:06:07,220  INFO TransactionFactoryInitiator:68 - HHH000399: Using default transaction strategy (direct JDBC transactions)
      00:06:07,226 DEBUG SettingsFactory:199 - Using BatchFetchStyle : LEGACY
      00:06:07,227 DEBUG SettingsFactory:218 - Maximum outer join fetch depth: 2
      00:06:07,227 DEBUG SettingsFactory:224 - Default batch fetch size: 1
      00:06:07,228 DEBUG SettingsFactory:230 - Generate SQL with comments: disabled
      00:06:07,228 DEBUG SettingsFactory:236 - Order SQL updates by primary key: disabled
      00:06:07,228 DEBUG SettingsFactory:242 - Order SQL inserts for batching: disabled
      00:06:07,229 DEBUG SettingsFactory:250 - Default null ordering: none
      00:06:07,230 DEBUG SettingsFactory:541 - Query translator: org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory
      00:06:07,234  INFO ASTQueryTranslatorFactory:48 - HHH000397: Using ASTQueryTranslatorFactory
      00:06:07,235 DEBUG SettingsFactory:260 - Query language substitutions: {}
      00:06:07,235 DEBUG SettingsFactory:266 - JPA-QL strict compliance: disabled
      00:06:07,236 DEBUG SettingsFactory:274 - Second-level cache: enabled
      00:06:07,236 DEBUG SettingsFactory:280 - Query cache: disabled
  
  
      00:06:07,842 DEBUG BeanNameUrlHandlerMapping:86 - Rejected bean name 'org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping': no URL paths identified
      00:06:07,843 DEBUG BeanNameUrlHandlerMapping:86 - Rejected bean name 'org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter': no URL paths identified
      00:06:07,843 DEBUG BeanNameUrlHandlerMapping:86 - Rejected bean name 'org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter': no URL paths identified
      00:06:07,843 DEBUG BeanNameUrlHandlerMapping:86 - Rejected bean name 'org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0': no URL paths identified
      00:06:07,843 DEBUG BeanNameUrlHandlerMapping:86 - Rejected bean name 'messageSource': no URL paths identified
      00:06:07,843 DEBUG BeanNameUrlHandlerMapping:86 - Rejected bean name 'localeChangeInterceptor': no URL paths identified
      00:06:07,844 DEBUG BeanNameUrlHandlerMapping:86 - Rejected bean name 'localeResolver': no URL paths identified
      00:06:07,844 DEBUG BeanNameUrlHandlerMapping:86 - Rejected bean name 'org.springframework.web.servlet.view.InternalResourceViewResolver#0': no URL paths identified
      00:06:07,844 DEBUG BeanNameUrlHandlerMapping:86 - Rejected bean name 'dataSource': no URL paths identified
      00:06:07,844 DEBUG BeanNameUrlHandlerMapping:86 - Rejected bean name 'sessionFactory': no URL paths identified
      00:06:07,845 DEBUG BeanNameUrlHandlerMapping:86 - Rejected bean name 'genericHibernateDAO': no URL paths identified
      00:06:07,845 DEBUG BeanNameUrlHandlerMapping:86 - Rejected bean name 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor': no URL paths identified
      00:06:07,845 DEBUG BeanNameUrlHandlerMapping:86 - Rejected bean name 'environment': no URL paths identified
      00:06:07,845 DEBUG BeanNameUrlHandlerMapping:86 - Rejected bean name 'systemProperties': no URL paths identified
      00:06:07,846 DEBUG BeanNameUrlHandlerMapping:86 - Rejected bean name 'systemEnvironment': no URL paths identified
      00:06:07,846 DEBUG BeanNameUrlHandlerMapping:86 - Rejected bean name 'servletConfig': no URL paths identified
      00:06:07,846 DEBUG BeanNameUrlHandlerMapping:86 - Rejected bean name 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry': no URL 
  
      00:06:07,886 DEBUG DefaultListableBeanFactory:215 - Creating shared instance of singleton bean 'org.springframework.web.servlet.view.InternalResourceViewResolver#0'
      00:06:07,886 DEBUG DefaultListableBeanFactory:435 - Creating instance of bean 'org.springframework.web.servlet.view.InternalResourceViewResolver#0'
      00:06:07,902 DEBUG DefaultListableBeanFactory:509 - Eagerly caching bean 'org.springframework.web.servlet.view.InternalResourceViewResolver#0' to allow for resolving potential circular references
      00:06:07,926 DEBUG DefaultListableBeanFactory:463 - Finished creating instance of bean 'org.springframework.web.servlet.view.InternalResourceViewResolver#0'
      00:06:07,927 DEBUG DefaultListableBeanFactory:246 - Returning cached instance of singleton bean 'dataSource'
      00:06:07,927 DEBUG DefaultListableBeanFactory:246 - Returning cached instance of singleton bean 'sessionFactory'
      00:06:07,927 DEBUG DefaultListableBeanFactory:215 - Creating shared instance of singleton bean 'genericHibernateDAO'
      00:06:07,928 DEBUG DefaultListableBeanFactory:435 - Creating instance of bean 'genericHibernateDAO'
      00:06:07,930 DEBUG InjectionMetadata:71 - Registered injected element on class [com.hdo.dao.GenericHibernateDAO]: AutowiredFieldElement for private org.hibernate.SessionFactory com.hdo.dao.GenericHibernateDAO.sessionFactory
      00:06:07,931 DEBUG DefaultListableBeanFactory:509 - Eagerly caching bean 'genericHibernateDAO' to allow for resolving potential circular references
      00:06:07,935 DEBUG InjectionMetadata:85 - Processing injected method of bean 'genericHibernateDAO': AutowiredFieldElement for private org.hibernate.SessionFactory com.hdo.dao.GenericHibernateDAO.sessionFactory
      00:06:07,935 DEBUG DefaultListableBeanFactory:246 - Returning cached instance of singleton bean 'sessionFactory'
      00:06:07,936 DEBUG AutowiredAnnotationBeanPostProcessor:433 - Autowiring by type from bean name 'genericHibernateDAO' to bean named 'sessionFactory'
      00:06:07,936 DEBUG DefaultListableBeanFactory:246 - Returning cached instance of singleton bean 'sessionFactory'
      00:06:07,937 DEBUG DefaultListableBeanFactory:463 - Finished creating instance of bean 'genericHibernateDAO'
      00:06:07,937 DEBUG DefaultListableBeanFactory:246 - Returning cached instance of singleton bean 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor'
      00:06:07,937 DEBUG XmlWebApplicationContext:858 - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@2f3fc03c]
      00:06:07,938 DEBUG DefaultListableBeanFactory:246 - Returning cached instance of singleton bean 'lifecycleProcessor'
  
  
      00:36:51,774 DEBUG DispatcherServlet:823 - DispatcherServlet with name 'spring' processing POST request for [/hpo/userHome.do]
  11:00:56,266 DEBUG ResponseStatusExceptionResolver:132 - Resolving exception from handler [public org.springframework.web.servlet.ModelAndView com.hdo.spring.controller.BasicController.goHome(com.hdo.model.User,java.util.Map&lt;java.lang.String, java.lang.Object&gt;,javax.servlet.http.HttpServletRequest)]: java.lang.NullPointerException
  11:00:56,267 DEBUG DefaultHandlerExceptionResolver:132 - Resolving exception from handler [public org.springframework.web.servlet.ModelAndView com.hdo.spring.controller.BasicController.goHome(com.hdo.model.User,java.util.Map&lt;java.lang.String, java.lang.Object&gt;,javax.servlet.http.HttpServletRequest)]: java.lang.NullPointerException
  11:00:56,269 DEBUG DispatcherServlet:959 - Could not complete request
  java.lang.NullPointerException
      at com.hdo.dao.GenericHibernateDAO.getCurrentSession(GenericHibernateDAO.java:27)
      at com.hdo.dao.GenericHibernateDAO.save(GenericHibernateDAO.java:33)
      at com.hdo.spring.controller.BasicController.goHome(BasicController.java:59)
      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:601)
      at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
      at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
      at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
      at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
      at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
      at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
      at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
  </code></pre>
  
  <p>I am totally new to spring mvc I guess I am dealing with multiple problems here, i get sessionFactory set to [null] and Rejected bean name 'sessionFactory'. I have tried using all latest jars in spring mvc3.2.2 and hibernate4. I couldnt figure out whats the issue, so please help ?</p>