title: Why do I get a "Null pointer exception" from spring security?
body: <p>I'm new to Spring Securityand can't see why I keep having the message with "Null Pointer Exception", I read the other posts and made some changes but keep having this error. It seems that it does not communiate with my database. Please help me. Thanks</p>
  
  <p>Here is my code:
  Dispatcher-servlet.xml</p>
  
  <pre><code>&gt;&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;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:p="http://www.springframework.org/schema/p"
  xmlns:jee="http://www.springframework.org/schema/jee"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="
  http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context.xsd
  http://www.springframework.org/schema/mvc
  http://www.springframework.org/schema/mvc/spring-mvc.xsd
  http://www.springframework.org/schema/jee
  http://www.springframework.org/schema/jee/spring-jee.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop.xsd
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx.xsd
  
  "&gt;
  
  &lt;bean id="viewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver"
  p:prefix="/WEB-INF/jsp/"
  p:suffix=".jsp"/&gt;
  
  &lt;bean id="filterMultipartResolver" 
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver"&gt; 
      &lt;property name="maxUploadSize" value="-1" /&gt;
  &lt;/bean&gt; 
  
  &lt;!-- a chaque espace de nom correspond un schema, les 2 points sont suivis d'un prefixe --&gt;
  &lt;!-- Dans schema location: A chaque schema est associe un fichier xsd  --&gt;
  &lt;context:component-scan base-package="demos.controller"/&gt;
  
  &lt;mvc:annotation-driven/&gt;
  &lt;tx:annotation-driven/&gt;
  &lt;context:annotation-config/&gt;
  
  &lt;bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /&gt;
  
  &lt;!-- Spring s'adresse au conteneur JPA de Glassfish. Le fichier persistence.xml situé dans META-INF du classpath est utilisé --&gt;
  &lt;jee:jndi-lookup id="entityManagerFactory" jndi-name="persistence/springsecuritybasicJNDI" /&gt;
  
  &lt;bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"/&gt;
  
  &lt;!--  Dao --&gt;
  &lt;bean id="roleDAO" class="demos.dao.RoleDAOImpl"/&gt;
  &lt;bean id="userDAO" class="demos.dao.UserDAOImpl"/&gt;
  
  
  &lt;bean id="domainUser" class="demos.model.User" scope="session"&gt;
      &lt;aop:scoped-proxy /&gt;
  &lt;/bean&gt;
  
  
  &lt;/beans&gt;
  </code></pre>
  
  <p>Spring Security.xml:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;beans:beans xmlns="http://www.springframework.org/schema/security"
      xmlns:beans="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:tx="http://www.springframework.org/schema/tx"
      xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
      http://www.springframework.org/schema/security
      http://www.springframework.org/schema/security/spring-security-4.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd"&gt;
  
  
      &lt;http auto-config="true" use-expressions="true"&gt;
          &lt;access-denied-handler error-page="/403Page.html"/&gt;
          &lt;intercept-url pattern="/sec/*" access="hasAnyRole('ROLE_MODERATOR','ROLE_ADMIN')" /&gt;
          &lt;intercept-url pattern="/admin/*" access="hasRole('ROLE_ADMIN')" /&gt;
  
          &lt;form-login login-page="/user-login.html"
              default-target-url="/success-login.html"
               authentication-failure-url="/error-login.html"
               login-processing-url="/j_spring_security_check"/&gt;
  
          &lt;logout logout-success-url="/success-logout.html"
           logout-url="/j_spring_security_logout"
            invalidate-session="true" /&gt;
  
      &lt;/http&gt;
  
      &lt;authentication-manager&gt;
          &lt;authentication-provider user-service-ref="MyUserDetail"&gt;
              &lt;password-encoder hash="plaintext" /&gt;
          &lt;/authentication-provider&gt;
      &lt;/authentication-manager&gt;
  
      &lt;beans:bean id="MyUserDetail" class="demos.service.CustomUserDetailsService" autowire="byType" /&gt;
  
  &lt;/beans:beans&gt;
  </code></pre>
  
  <p>My customerDetailsService:</p>
  
  <pre><code>package demos.service;
  
  import java.util.ArrayList;
  import java.util.Collection;
  import java.util.List;
  
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.security.core.GrantedAuthority;
  import org.springframework.security.core.authority.SimpleGrantedAuthority;
  import org.springframework.security.core.userdetails.User;
  import org.springframework.security.core.userdetails.UserDetails;
  import org.springframework.security.core.userdetails.UserDetailsService;
  import org.springframework.security.core.userdetails.UsernameNotFoundException;
  import org.springframework.stereotype.Service;
  import org.springframework.transaction.annotation.Transactional;
  
  import demos.dao.UserDAO;
  
  
  @Service
  @Transactional(readOnly=true)
  public class CustomUserDetailsService implements UserDetailsService {
  
      @Autowired
      private UserDAO userDAO;    
  
      public UserDetails loadUserByUsername(String login)
              throws UsernameNotFoundException {
  
          // Declare a null Spring User
          UserDetails user = null;
  
          System.out.println("serviceLogin: "+login);
          demos.model.User domainUser = userDAO.getUser(login);
  
          if(domainUser == null){
              throw new UsernameNotFoundException("UserName "+login+" not found");
          }
  
          boolean enabled = true;
          boolean accountNonExpired = true;
          boolean credentialsNonExpired = true;
          boolean accountNonLocked = true;
  System.out.println("loginuser: " + domainUser.getLogin() );
  
          user = new User(
                  domainUser.getLogin(), 
                  domainUser.getPassword(), 
                  enabled, 
                  accountNonExpired, 
                  credentialsNonExpired, 
                  accountNonLocked,
                  getAuthorities(domainUser.getRole().getId()) );
  
          return user;
  
      }
  
  
      public Collection&lt;? extends GrantedAuthority&gt; getAuthorities(Integer role) {
          List&lt;GrantedAuthority&gt; authList = getGrantedAuthorities(getRoles(role));
          return authList;
      }
  
      public List&lt;String&gt; getRoles(Integer role) {
  
          List&lt;String&gt; roles = new ArrayList&lt;String&gt;();
  
          if (role.intValue() == 1) {
              roles.add("ROLE_MODERATOR");
              roles.add("ROLE_ADMIN");
          } else if (role.intValue() == 2) {
              roles.add("ROLE_MODERATOR");
          }
          return roles;
      }
  
      public static List&lt;GrantedAuthority&gt; getGrantedAuthorities(List&lt;String&gt; roles) {
          List&lt;GrantedAuthority&gt; authorities = new ArrayList&lt;GrantedAuthority&gt;();
  
          for (String role : roles) {
              authorities.add(new SimpleGrantedAuthority(role));
          }
          return authorities;
      }
  
  }
  </code></pre>
  
  <p>Here is the UserDao:</p>
  
  <pre><code>package demos.dao;
  
  import java.util.ArrayList;
  import java.util.List;
  
  import javax.persistence.EntityManager;
  import javax.persistence.PersistenceContext;
  import javax.persistence.TypedQuery;
  
  import org.springframework.stereotype.Repository;
  
  import demos.model.User;
  
  
  @Repository
  public class UserDAOImpl implements UserDAO {
  
      @PersistenceContext
      private EntityManager em;
  
  
      @Override
      public User getUser(String login) {
  
          System.out.println("daoLogin1: "+ login);
  
          List&lt;User&gt; userList = new ArrayList&lt;User&gt;();
  
          System.out.println("daoLogin2: "+login);
  
          String query = "select u from User u where u.login like ?1 ";
          TypedQuery&lt;User&gt; q = em.createQuery(query,User.class); 
          q.setParameter(1, login);
  //      q.setParameter(1, '%'+login+'%');
          userList = q.getResultList();
          if (userList.size() &gt; 0)
              return userList.get(0);
          else
              return null;    
      }
  
  }
  </code></pre>
  
  <p>Here is the UserService layer:</p>
  
  <pre><code>package demos.service;
  
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.stereotype.Service;
  import org.springframework.transaction.annotation.Transactional;
  
  import demos.dao.UserDAO;
  import demos.model.User;
  
      @Service
      @Transactional
      public class UserServiceImpl implements UserService {
  
          @Autowired
          private UserDAO userDAO;
  
          public User getUser(String login) {
              return userDAO.getUser(login);
          }
  
  
  }
  </code></pre>
  
  <p>And the User class:</p>
  
  <pre><code>package demos.model;
  
  import java.io.Serializable;
  
  import javax.persistence.CascadeType;
  import javax.persistence.Entity;
  import javax.persistence.GeneratedValue;
  import javax.persistence.Id;
  import javax.persistence.JoinColumn;
  import javax.persistence.JoinTable;
  import javax.persistence.OneToOne;
  import javax.persistence.Table;
  
  @Entity
  @Table(name="users")
  public class User implements Serializable{
  
      @Id
      @GeneratedValue
      private Integer id;
  
      private String login;
  
      private String password;
  
      @OneToOne(cascade=CascadeType.ALL)
      @JoinTable(name="user_roles",
          joinColumns = {@JoinColumn(name="user_id", referencedColumnName="id")},
          inverseJoinColumns = {@JoinColumn(name="role_id", referencedColumnName="id")}
      )
      private Role role;
  
  
      //getter et setter
  
      public Integer getId() {
          return id;
      }
  
      public void setId(Integer id) {
          this.id = id;
      }
  
      public String getLogin() {
          return login;
      }
  
      public void setLogin(String login) {
          this.login = login;
      }
  
      public String getPassword() {
          return password;
      }
  
      public void setPassword(String password) {
          this.password = password;
      }
  
      public Role getRole() {
          return role;
      }
  
      public void setRole(Role role) {
          this.role = role;
      }
  
      @Override
      public String toString() {
          return "User [id=" + id + ", login=" + login + ", password=" + password
                  + ", role=" + role + "]";
      }
  
  
  }
  </code></pre>
  
  <p>With the Role Class:</p>
  
  <pre><code>package demos.model;
  
  import java.io.Serializable;
  import java.util.Set;
  
  import javax.persistence.CascadeType;
  import javax.persistence.Entity;
  import javax.persistence.GeneratedValue;
  import javax.persistence.Id;
  import javax.persistence.JoinColumn;
  import javax.persistence.JoinTable;
  import javax.persistence.OneToMany;
  import javax.persistence.Table;
  
  @Entity
  @Table(name="roles")
  public class Role implements Serializable{
  
      @Id
      @GeneratedValue
      private Integer id;
  
      private String role;
  
      @OneToMany(cascade=CascadeType.ALL)
      @JoinTable(name="user_roles", 
          joinColumns = {@JoinColumn(name="role_id", referencedColumnName="id")},
          inverseJoinColumns = {@JoinColumn(name="user_id", referencedColumnName="id")}
      )
      private Set&lt;User&gt; userRoles;
  
  
      public Integer getId() {
          return id;
      }
  
      public void setId(Integer id) {
          this.id = id;
      }
  
      public String getRole() {
          return role;
      }
  
      public void setRole(String role) {
          this.role = role;
      }
  
      public Set&lt;User&gt; getUserRoles() {
          return userRoles;
      }
  
      public void setUserRoles(Set&lt;User&gt; userRoles) {
          this.userRoles = userRoles;
      }
  
      @Override
      public String toString() {
          return "Role [id=" + id + ", role=" + role + ", userRoles=" + userRoles
                  + "]";
      }
  
  
  }
  </code></pre>
  
  <p>Here is the message that I get:</p>
  
  <pre><code>Caused by: java.lang.NullPointerException
      at demos.service.CustomUserDetailsService.loadUserByUsername(CustomUserDetailsService.java:34)
      at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114)
      ... 56 more
  
  |Infos: serviceLogin: adm
  </code></pre>
  
  <p>Let me know if you need more details, but I cannot see what is wrong.</p>