Q:

Service class not instantiating during @ManageProperty call in Spring + Hibernate + JSF + PrimeFaces + Maven

I'm beginner for Spring and JSF I need to develop application working with Spring + JSF + PrimeFace + Hibernate + Maven I make a sample application but there have a some exceptions I cannot find what is the wrong with me please help me
project structre 

web.xml
<? xml version="1.0" encoding="UTF-8"? >
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <display-name>PrimeFaces Web Application</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext.xml
        </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context. ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>
            org.springframework.web.context.request. RequestContextListener
        </listener-class>
    </listener>
    <!--  Change to "Production" when you are ready to deploy -->
    <context-param>
        <param-name>javax.faces. PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>

    <!--  Welcome page -->
    <welcome-file-list>
        <welcome-file>faces/index.xhtml</welcome-file>
    </welcome-file-list>

    <!--  JSF mapping -->
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp. FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!--  Map these files with JSF -->
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.faces</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>

</web-app>

applicationContext.xml
<? xml version="1.0" encoding="UTF-8"? >
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    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.0.xsd
        http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
    <context:component-scan base-package="com.example.spring" />
    <context:annotation-config />
    <context:spring-configured />
    <!--  Data Source Declaration -->
    <bean id="DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc. Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/sptest" />
        <property name="user" value="root" />
        <property name="password" value="hc@123" />
    </bean>

    <!--  Session Factory Declaration -->
    <bean id="SessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="DataSource" />

        <property name="packagesToScan">
            <list>
                <value>com.example.spring.model</value>
            </list>
        </property>
        <!--  <property name="annotatedClasses"> <list> <value>net.javabeat.spring.model. Customer</value> 
            </list> </property> -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect. MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
            </props>
        </property>
    </bean>

    <!--  Enable the configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="txManager" />

    <!--  Transaction Manager is defined -->
    <bean id="txManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="SessionFactory" />
    </bean>

</beans>

faces-config.xml
<? xml version="1.0" encoding="utf-8"? >
<faces-config 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-facesconfig_2_0.xsd"
    version="2.0">
    <application>
        <el-resolver>org.springframework.web.jsf.el. SpringBeanFacesELResolver</el-resolver>
    </application>

</faces-config>

User.java
package com.example.spring.model;

import java.io. Serializable;
import javax.persistence. Basic;
import javax.persistence. Column;
import javax.persistence. Entity;
import javax.persistence. GeneratedValue;
import javax.persistence. GenerationType;
import javax.persistence. Id;
import javax.persistence. NamedQueries;
import javax.persistence. NamedQuery;
import javax.persistence. Table;

/**
 *
 * @author Hashan Chamikara
 */
@Entity
@Table(name = "user")
@NamedQueries({
    @NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")})
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType. IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Basic(optional = false)
    @Column(name = "username")
    private String username;
    @Basic(optional = false)
    @Column(name = "password")
    private String password;
    @Basic(optional = false)
    @Column(name = "first_name")
    private String firstName;
    @Basic(optional = false)
    @Column(name = "last_name")
    private String lastName;
    @Basic(optional = false)
    @Column(name = "status")
    private int status;

    public User() {
    }

    public User(Integer id) {
        this.id = id;
    }

    public User(Integer id, String username, String password, String firstName, String lastName, int status) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.firstName = firstName;
        this.lastName = lastName;
        this.status = status;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id ! = null ?  id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!( object instanceof User)) {
            return false;
        }
        User other = (User) object;
        if ((this.id == null && other.id ! = null) || (this.id ! = null && ! this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.iquebox.admin.models. User[ id=" + id + " ]";
    }

}

UserDAO.java
package com.example.spring.dao;

import org.hibernate. SessionFactory;
import org.hibernate.criterion. Restrictions;
import org.springframework.beans.factory.annotation. Autowired;
import org.springframework.stereotype. Repository;

import com.example.spring.model. User;

@Repository
public class UserDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public boolean login(String username, String password) {
        User user = (User) getSessionFactory().getCurrentSession().createCriteria(User.class)
                .add(Restrictions.and(Restrictions.eq("username", username), Restrictions.eq("password", password)))
                .uniqueResult();
        return user ! = null;
    }
}

UserService.java
package com.example.spring.service;

import org.springframework.beans.factory.annotation. Autowired;
import org.springframework.stereotype. Service;

import com.example.spring.dao. UserDAO;

@Service
public class UserService {

    @Autowired
    private UserDAO userDAO;

    public UserDAO getUserDAO() {
        return userDAO;
    }

    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public boolean login(String username, String password){
        return getUserDAO().login(username, password);
    }
}

UserManagedBean.java
package com.example.managedBean;

import java.io. Serializable;

import javax.faces.application. FacesMessage;
import javax.faces.bean. ManagedBean;
import javax.faces.bean. ManagedProperty;
import javax.faces.bean. RequestScoped;
import javax.faces.context. FacesContext;
import javax.faces.event. ActionEvent;

import org.primefaces.context. RequestContext;
import com.example.spring.service. UserService;

@ManagedBean(name = "userMB")
@RequestScoped
public class UserManagedBean implements Serializable {

    private static final long serialVersionUID = 1L;

    @ManagedProperty("#{UserService}")
    UserService userService;

    private String username;
    private String password;

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void login(ActionEvent event) {
        RequestContext context = RequestContext.getCurrentInstance();
        FacesMessage message = null;
        boolean loggedIn = false;

        if(username ! = null  && password ! = null && userService.login(username, password)) {
            loggedIn = true;
            message = new FacesMessage(FacesMessage. SEVERITY_INFO, "Welcome", username);
        } else {
            loggedIn = false;
            message = new FacesMessage(FacesMessage. SEVERITY_WARN, "Loggin Error", "Invalid credentials");
        }

        FacesContext.getCurrentInstance().addMessage(null, message);
        context.addCallbackParam("loggedIn", loggedIn);
    } 

}

index.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui">
<h:head>
    <title>Login Example</title>
</h:head>
<h:body onload="PF('dlg').show();">
    <h:form>
        <p:growl id="growl" sticky="true" showDetail="true" life="3000" />

        <p:dialog header="Login" widgetVar="dlg" modal="true" closable="false"
            resizable="false">
            <h:panelGrid columns="2" cellpadding="5">
                <h:outputLabel for="username" value="Username:" />
                <p:inputText id="username" value="#{userMB.username}"
                    required="true" label="username" />

                <h:outputLabel for="password" value="Password:" />
                <p:password id="password" value="#{userMB.password}" required="true"
                    label="password" />

                <f:facet name="footer">
                    <p:commandButton value="Login" update="growl"
                        actionListener="#{userMB.login}"
                        oncomplete="handleLoginRequest(xhr, status, args)" />
                </f:facet>
            </h:panelGrid>
        </p:dialog>
    </h:form>

    <script type="text/javascript">
        function handleLoginRequest(xhr, status, args) {
            if (args.validationFailed || ! args.loggedIn) {
                PF('dlg').jq.effect("shake", {
                    times : 5
                }, 100);
            } else {
                PF('dlg').hide();
                $('#loginLink').fadeOut();
            }
        }
    </script>
</h:body>
</html>

Exception in tomcat
Oct 22, 2015 3:43:30 PM com.sun.faces.lifecycle. InvokeApplicationPhase execute
WARNING: /index.xhtml @26,60 actionListener="#{userMB.login}": java.lang. NullPointerException
javax.el. ELException: /index.xhtml @26,60 actionListener="#{userMB.login}": java.lang. NullPointerException
    at com.sun.faces.facelets.el. TagMethodExpression.invoke(TagMethodExpression.java:111)
    at javax.faces.event. MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:147)
    at javax.faces.event. ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component. UIComponentBase.broadcast(UIComponentBase.java:814)
    at javax.faces.component. UICommand.broadcast(UICommand.java:300)
    at javax.faces.component. UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component. UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle. InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle. Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle. LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp. FacesServlet.service(FacesServlet.java:658)
    at org.apache.catalina.core. ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core. ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server. WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core. ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core. ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core. StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core. StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator. AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    at org.apache.catalina.core. StandardHostValve.invoke(StandardHostValve.java:136)
    at org.apache.catalina.valves. ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves. AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core. StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector. CoyoteAdapter.service(CoyoteAdapter.java:526)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
    at org.apache.coyote. AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net. NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
    at org.apache.tomcat.util.net. NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
    at java.util.concurrent. ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent. ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads. TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang. Thread.run(Thread.java:745)
Caused by: java.lang. NullPointerException
    at com.example.managedBean. UserManagedBean.login(UserManagedBean.java:56)
    at sun.reflect. NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect. NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect. DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect. Method.invoke(Method.java:497)
    at org.apache.el.parser. AstValue.invoke(AstValue.java:245)
    at org.apache.el. MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
    at com.sun.faces.facelets.el. TagMethodExpression.invoke(TagMethodExpression.java:105)
    ... 32 more

Oct 22, 2015 3:43:30 PM com.sun.faces.context. AjaxExceptionHandlerImpl handlePartialResponseError
SEVERE: java.lang. NullPointerException
    at com.example.managedBean. UserManagedBean.login(UserManagedBean.java:56)
    at sun.reflect. NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect. NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect. DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect. Method.invoke(Method.java:497)
    at org.apache.el.parser. AstValue.invoke(AstValue.java:245)
    at org.apache.el. MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
    at com.sun.faces.facelets.el. TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.event. MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:147)
    at javax.faces.event. ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component. UIComponentBase.broadcast(UIComponentBase.java:814)
    at javax.faces.component. UICommand.broadcast(UICommand.java:300)
    at javax.faces.component. UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component. UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle. InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle. Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle. LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp. FacesServlet.service(FacesServlet.java:658)
    at org.apache.catalina.core. ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core. ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server. WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core. ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core. ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core. StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core. StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator. AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    at org.apache.catalina.core. StandardHostValve.invoke(StandardHostValve.java:136)
    at org.apache.catalina.valves. ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves. AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core. StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector. CoyoteAdapter.service(CoyoteAdapter.java:526)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
    at org.apache.coyote. AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net. NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
    at org.apache.tomcat.util.net. NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
    at java.util.concurrent. ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent. ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads. TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang. Thread.run(Thread.java:745)

Oct 22, 2015 4:02:29 PM org.apache.catalina.core. StandardContext reload
INFO: Reloading Context with name [/spring] has started
Oct 22, 2015 4:02:29 PM org.apache.catalina.core. ApplicationContext log
INFO: Closing Spring root WebApplicationContext
Oct 22, 2015 4:02:29 PM org.springframework.web.context.support. XmlWebApplicationContext doClose
INFO: Closing Root WebApplicationContext: startup date [Thu Oct 22 15:42:12 IST 2015]; root of context hierarchy
Oct 22, 2015 4:02:29 PM org.apache.catalina.loader. WebappClassLoader clearReferencesJdbc
WARNING: The web application [/spring] registered the JDBC driver [com.mysql.jdbc. Driver] but failed to unregister it when the web application was stopped.  To prevent a memory leak, the JDBC Driver has been forcibly unregistered. 
Oct 22, 2015 4:02:29 PM org.apache.catalina.loader. WebappClassLoader clearReferencesThreads
WARNING: The web application [/spring] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it.  This is very likely to create a memory leak.  Stack trace of thread:
 java.lang. Object.wait(Native Method)
 java.lang.ref. ReferenceQueue.remove(ReferenceQueue.java:143)
 com.mysql.jdbc. AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:43)
Oct 22, 2015 4:02:29 PM org.apache.catalina.loader. WebappClassLoader clearReferencesThreads
WARNING: The web application [/spring] appears to have started a thread named [Mojarra-WebResourceMonitor-1-thread-1] but has failed to stop it.  This is very likely to create a memory leak.  Stack trace of thread:
 sun.misc. Unsafe.park(Native Method)
 java.util.concurrent.locks. LockSupport.parkNanos(LockSupport.java:215)
 java.util.concurrent.locks. AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2078)
 java.util.concurrent. ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1093)
 java.util.concurrent. ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:809)
 java.util.concurrent. ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
 java.util.concurrent. ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
 java.util.concurrent. ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
 java.lang. Thread.run(Thread.java:745)

A:

You are getting NullPointerException in login method in UserManagedBean object.  It is probably caused by null userService which might be injected in a wrong way.  Try changing:
 @ManagedProperty("#{UserService}")

to:
 @ManagedProperty("#{userService}")

