0

I need help in setting up my spring applciation. I am getting null pointer exception while accessing the @Autowired fields in @Service and @Repository classes. But I am getting proper value in @Controller class. I tried to debug. In DEBUG mode when the application starts then the value of fields userDao and dataSource are fetching proper value but once the server starts the values are null when I try to debug by traversing the actual flow. Here is my servlet-context.xml

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

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

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

</beans:beans>

Here is my Controller class which works perfectly fine with autowiring of UserService.

@Controller
public class HomeController {

    @Autowired
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
@RequestMapping(value = "/register", method = RequestMethod.POST)
    public ModelAndView register(HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView();
        String result = userService.createUser(request);
        if(result.equals("SUCCESS"))
        {
            modelAndView.addObject("user",request.getParameter("firstname"));
            modelAndView.setViewName("scramble");
        }
        else
            modelAndView.setViewName("registrationerror");
        return modelAndView;
    }

}

Here is my UserServiceImpl class where the autowire of userDao gives NullPointerException.

@Service("UserService")
public class UserServiceImpl implements UserService, UserDetailsService{

    private UserDao userDao;

    public UserDao getUserDao() {
        return userDao;
    }

    @Autowired
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public String createUser(HttpServletRequest request) {
        User user = new User();
        SecurePasswordGenerator secGenerator = new SecurePasswordGenerator();
        String hashedPassword = secGenerator.passwordGeneratorFunction(request.getParameter("password"));
        user.setFirstname(request.getParameter("firstname"));
        user.setLastname(request.getParameter("lastname"));
        user.setEmail(request.getParameter("email"));
        user.setHashedPass(hashedPassword);
        user.setAddress(request.getParameter("address"));
        user.setZipcode(request.getParameter("zipcode"));

        user.setAge(Integer.parseInt(request.getParameter("age")));
        String result = userDao.createUser(user);
        return result;
    }
}

Here is my UserDaoImpl class in which autowiring of dataSource gives NullPointerException.

@Repository("UserDao")
public class UserDaoImpl implements UserDao{


    private DataSource dataSource;
    @Autowired
    public void setDataSource(DataSource dataSource) {
       this.dataSource = dataSource;
    }

    protected final Log logger = LogFactory.getLog(getClass());  

    @Override
    public String createUser(User user)
    {
        try {
            String insertUserSQL = "INSERT INTO USER (FIRSTNAME, LASTNAME, EMAIL, PASSKEY, ADDRESS, ZIPCODE, AGE) VALUES (?, ?, ?, ?, ?, ?)";
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            jdbcTemplate.update(insertUserSQL,  
                             new Object[] { user.getFirstname(), user.getLastname(), user.getEmail(),  
                      user.getHashedPass(), user.getAddress(), user.getZipcode(), user.getAge() });
            return "SUCCESS";
        } catch (Exception e) {
            e.printStackTrace();
            return "FAILURE";
        }
    }

}

I am also providing my root-context.xml where I have declared my Authentication and datasource.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:sec="http://www.springframework.org/schema/security"
    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.xsd
                        http://www.springframework.org/schema/security 
                        http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <!-- Root Context: defines shared resources visible to all other web components -->
    <sec:http auto-config="true" use-expressions="true" access-denied-page="/denied">
        <sec:intercept-url pattern="/home" access="isAnonymous()" />
        <sec:intercept-url pattern="/login" access="isAnonymous()" />
        <sec:intercept-url pattern="/logout" access="isAnonymous()" />   
        <sec:intercept-url pattern="/scramble" access="isAuthenticated()"></sec:intercept-url>      
        <sec:form-login login-page="/login" default-target-url="/home" authentication-failure-url="/error" />
        <sec:logout
            invalidate-session="true"
            delete-cookies="SPRING_SECURITY_REMEMBER_ME_COOKIE"
            logout-success-url="/logout"/>              
    </sec:http>
    <sec:authentication-manager >
        <sec:authentication-provider user-service-ref="userService">
            <sec:password-encoder ref="encoder"/>
        </sec:authentication-provider>  
    </sec:authentication-manager>

    <!-- declare datasource bean -->  
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
        <property name="url" value="jdbc:mysql://localhost:3306/english_words" />  
        <property name="username" value="root" />  
        <property name="password" value="root" />  
    </bean> 

    <bean id="userService" class="com.unscramble.serviceImpl.UserServiceImpl"/>

    <!-- For hashing and salting user passwords -->
    <bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

</beans>

Below is the error I am getting.

Aug 16, 2014 10:51:54 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet appServlet threw exception
java.lang.NullPointerException
    at com.unscramble.serviceImpl.UserServiceImpl.createUser(UserServiceImpl.java:43)
    at com.unscramble.controller.HomeController.register(HomeController.java:69)
    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:213)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:311)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:101)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:173)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
    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:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
    at 

org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) at java.lang.Thread.run(Thread.java:722)

Thanks in advance. I am using spring 3.1.0 . Let me know if any further information are needed.

Adding the spring log as requested.

Aug 17, 2014 11:53:10 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.7.0_11\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jdk1.7.0_11/bin/../jre/bin/server;C:/Program Files/Java/jdk1.7.0_11/bin/../jre/bin;C:/Program Files/Java/jdk1.7.0_11/bin/../jre/lib/amd64;C:\Program Files\Java\jdk1.7.0_11/bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files\apache-ant-1.9.4-bin/bin;C:\Program Files (x86)\MySQL\MySQL Utilities 1.3.6\;G:\Android\eclipse;;.
Aug 17, 2014 11:53:10 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Unscramble' did not find a matching property.
Aug 17, 2014 11:53:10 AM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
Aug 17, 2014 11:53:10 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 609 ms
Aug 17, 2014 11:53:10 AM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Aug 17, 2014 11:53:10 AM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.37
Aug 17, 2014 11:53:11 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Sun Aug 17 11:53:11 IST 2014]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/root-context.xml]
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@8bc1115: defining beans [org.springframework.security.filterChains,org.springframework.security.filterChainProxy,org.springframework.security.web.PortMapperImpl#0,org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0,org.springframework.security.authentication.ProviderManager#0,org.springframework.security.web.context.HttpSessionSecurityContextRepository#0,org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy#0,org.springframework.security.web.savedrequest.HttpSessionRequestCache#0,org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler#0,org.springframework.security.access.vote.AffirmativeBased#0,org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0,org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator#0,org.springframework.security.authentication.AnonymousAuthenticationProvider#0,org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint#0,org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0,org.springframework.security.userDetailsServiceFactory,org.springframework.security.web.DefaultSecurityFilterChain#0,org.springframework.security.authentication.dao.DaoAuthenticationProvider#0,org.springframework.security.authentication.DefaultAuthenticationEventPublisher#0,org.springframework.security.authenticationManager,userService,encoder]; root of factory hierarchy
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 993 ms
Aug 17, 2014 11:53:12 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'appServlet'
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'appServlet-servlet': startup date [Sun Aug 17 11:53:12 IST 2014]; parent: Root WebApplicationContext
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]
INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@43a0ddf: defining beans [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.web.servlet.view.InternalResourceViewResolver#0,homeController,loginController,UserDao,UserService,dataSource,userDao,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@8bc1115
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/register],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.ModelAndView com.unscramble.controller.HomeController.register(javax.servlet.http.HttpServletRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/home],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.ModelAndView com.unscramble.controller.HomeController.home()
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/unscramble],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.ModelAndView com.unscramble.controller.HomeController.unscramble(java.lang.String)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signup],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.ModelAndView com.unscramble.controller.HomeController.signup()
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/login],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.ModelAndView com.unscramble.controller.LoginController.login(java.lang.String,java.lang.String,java.lang.String)
INFO : org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization completed in 1473 ms
Aug 17, 2014 11:53:13 AM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
Aug 17, 2014 11:53:13 AM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Aug 17, 2014 11:53:13 AM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/22  config=null
Aug 17, 2014 11:53:13 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 3305 ms
Aug 17, 2014 11:54:08 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet appServlet threw exception
java.lang.NullPointerException
    at com.unscramble.serviceImpl.UserServiceImpl.createUser(UserServiceImpl.java:45)
    at com.unscramble.controller.HomeController.register(HomeController.java:69)
    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:213)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)

I have also tried making few changes to show my error in more specific way. I have added a system.print statement in setUserDao method and also just before the userDao.createUser line in UserServiceImpl.java. So my UserServiceImpl looks like

@Autowired
    @Qualifier("UserDao")
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
        System.out.println("The userDao is set and the value is : " + userDao);
    }

    @Override
    public String createUser(HttpServletRequest request) {

        <more code here>

        user.setAge(Integer.parseInt(request.getParameter("age")));
        System.out.println("The userDao in createUser has value : " + userDao);
        String result = userDao.createUser(user);
        return result;
    }

As I have said earlier during server start it prints userDao value. But once the server started and I try to access page. In the main flow userDao is printed as null. You can check the below log I am pasting. Check the first line from top and third or fourth line from bottom to see the difference.

    <few logs here> 
The userDao is set and the value is : com.unscramble.daoImpl.UserDaoImpl@2665d910
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization completed in 1427 ms
Aug 17, 2014 12:35:49 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
Aug 17, 2014 12:35:49 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Aug 17, 2014 12:35:49 PM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/26  config=null
Aug 17, 2014 12:35:49 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 3201 ms
The userDao in createUser has value : null
Aug 17, 2014 12:36:45 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet appServlet threw exception
java.lang.NullPointerException
    at com.unscramble.serviceImpl.UserServiceImpl.createUser(UserServiceImpl.java:47)
  • More helpful than the stack trace would be Spring's log output when it was creating the contexts. My first guess at solving your problem would be to add @Qualifier("UserDao") in UserServiceImpl.setUserDao method. – Paul Aug 16 '14 at 17:32
  • As an aside, only create interfaces when you need them. That is, if you only have one implementation of an interface then get rid of the interface. Obviously I don't know if this applies here and it's not applicable to every situation but I've seen so many unneeded interfaces over the years that it's worth a mention. – Paul Aug 16 '14 at 17:35
  • I tried to edit my first comment but hit "save" after the 5 minute limit. What I wanted to add to my first comment was: I don't think this will solve your problem. Exactly which line throws the NPE? I'm assuming it's `userDao.createUser` and not actually the line before it. – Paul Aug 16 '14 at 17:41
  • try adding `` `` declares support for general annotations such as `@Required`, `@Autowired`, `@PostConstruct`, and so on. – Ankur Singhal Aug 16 '14 at 17:48
  • @Paul "only create interfaces when you need them" - I would be careful with such statement. – Pavel Horal Aug 16 '14 at 20:15
  • @techgig The issue might be mess in your context hierarchy - your service is defined in the root context, but your DAO would be in servlet context. Root context does not see child context beans. Also the *component scan* in your servlet context will probably detect your UserServiceImpl as well (duplicate bean definition). – Pavel Horal Aug 16 '14 at 20:19
  • @Pavel Horal How can I resolve the mess can you please suggest how can I make changes to my servlet-context.xml and root-context.xml so that I can solve the issue. Also I havent declared my DAO in servlet-context.xml because I thought that if `@Services` and `@Transaction` are used I need not explicitly declare the DAO in xml. Even when I tried declaring DAO in servlet-context.xml or root-context.xml the error persisted. – Mani manasa mylavarapu Aug 17 '14 at 06:39
  • @ankur-singhal I added `` to servlet-context.xml but that didnt solve the problem. – Mani manasa mylavarapu Aug 17 '14 at 06:42
  • @Paul I added `@Qualifier("UserDao")` but that didnt solve the problem. Yes you are correct the NPE is given by line `userDao.createUser`. In the exception log I have provided it also shows the error on the same line. `java.lang.NullPointerException at com.unscramble.serviceImpl.UserServiceImpl.createUser(UserServiceImpl.java:43)` I have edited my post and provided the spring log that you required – Mani manasa mylavarapu Aug 17 '14 at 06:43

1 Answers1

0

the only thing looks odd to me in your code is you have specified getter funtions before setter functions please declare getter after the setter functions and check if its works .Some time its due to server problem , clean your server and restart it .