title: How to get rid of this exception " No bean named 'userDetailsService' is defined" although it is defined in xml file?
body: <p>I am trying spring security authentication using database facing issues </p>
  
  <p>DataController.java</p>
  
  <pre><code>package com.anzy.controller;
  import java.util.List;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.stereotype.Controller;
  import org.springframework.web.bind.annotation.ModelAttribute;
  import org.springframework.web.bind.annotation.RequestMapping;
  import org.springframework.web.bind.annotation.RequestParam;
  import org.springframework.web.servlet.ModelAndView;
  
  import com.anzy.dao.DataDao;
  import com.anzy.domain.Employee;
  @Controller
  public class DataController {
  
   @Autowired
   DataDao dataDao;
  
   @RequestMapping("form")
   public ModelAndView getForm(@ModelAttribute Employee employee) {
    return new ModelAndView("form");
   }
  
   @RequestMapping("register")
   public ModelAndView registerUser(@ModelAttribute Employee employee) {
       dataDao.insertRow(employee);
    return new ModelAndView("redirect:list");
   }
  
   @RequestMapping("list")
   public ModelAndView getList() 
   {
    List employeeList = dataDao.getList();
  
    return new ModelAndView("list", "employeeList", employeeList);
   }
  
   @RequestMapping("delete")
   public ModelAndView deleteUser(@RequestParam int id) {
       dataDao.deleteRow(id);
    return new ModelAndView("redirect:list");
   }
  
   @RequestMapping("edit")
   public ModelAndView editUser(@RequestParam int id,
     @ModelAttribute Employee employee) {
    Employee employeeObject = dataDao.getRowById(id);
    return new ModelAndView("edit", "employeeObject", employeeObject);
   }
  
   @RequestMapping("update")
   public ModelAndView updateUser(@ModelAttribute Employee employee) {
       dataDao.updateRow(employee);
    return new ModelAndView("redirect:list");
   }
  
  }
  </code></pre>
  
  <p>User.java</p>
  
  <pre><code>package com.anzy.domain;
  
  import java.io.Serializable;
  import java.util.List;
  
  import javax.persistence.Column;
  import javax.persistence.Entity;
  import javax.persistence.EnumType;
  import javax.persistence.Enumerated;
  import javax.persistence.GeneratedValue;
  import javax.persistence.GenerationType;
  import javax.persistence.Id;
  import javax.persistence.JoinColumn;
  import javax.persistence.JoinTable;
  import javax.persistence.ManyToMany;
  
  @Entity
  public class User implements Serializable
  {
      /**
       * 
       */
      private static final long serialVersionUID = 1L;
  
      @Id
      @GeneratedValue(strategy=GenerationType.AUTO)
      private int id;
  
      @Column(name="username")
      private String username;
  
      @Column(name="password")
      private String password;
      @ManyToMany
      @JoinTable(name="UserAndRoles",joinColumns=@JoinColumn(name="user_id"),inverseJoinColumns=@JoinColumn(name="role_id"))
      private List&lt;Role&gt; roles;
  
      @Enumerated(EnumType.STRING)
      private UserStatus status;
  
      public int getId() {
          return id;
      }
      public void setId(int 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 UserStatus getStatus() {
          return status;
      }
      public void setStatus(UserStatus status) {
          this.status = status;
      }
      public List&lt;Role&gt; getRoles() {
          return roles;
      }
      public void setRoles(List&lt;Role&gt; roles) {
          this.roles = roles;
      }
  
  }
  </code></pre>
  
  <p>Role.java</p>
  
  <pre><code>package com.anzy.domain;
  
  import java.util.List;
  
  import javax.persistence.Column;
  import javax.persistence.GeneratedValue;
  import javax.persistence.GenerationType;
  import javax.persistence.Id;
  import javax.persistence.ManyToMany;
  
  public class Role
  {
      @Id
      @GeneratedValue(strategy=GenerationType.AUTO)
      private int id;
  
      @Column(name="roleName")
      private String roleName;
      @ManyToMany(mappedBy="roles")
      private List&lt;User&gt;users;
  
      public Role(int id, String roleName, List&lt;User&gt; users)
      {
          super();
          this.id = id;
          this.roleName = roleName;
          this.users = users;
      }
      public int getId() {
          return id;
      }
      public void setId(int id) {
          this.id = id;
      }
      public String getRoleName() {
          return roleName;
      }
      public void setRoleName(String roleName) {
          this.roleName = roleName;
      }
      public List&lt;User&gt; getUsers() {
          return users;
      }
      public void setUsers(List&lt;User&gt; users) {
          this.users = users;
      }
  
  
  }
  </code></pre>
  
  <p>UserStatus.java</p>
  
  <pre><code>package com.anzy.domain;
  
  public enum UserStatus 
  {
      ACTIVE,
      INACTIVE;
  
  }
  </code></pre>
  
  <p>Employee.java</p>
  
  <pre><code>package com.anzy.domain;
  
  import javax.persistence.Column;
  import javax.persistence.Entity;
  import javax.persistence.GeneratedValue;
  import javax.persistence.Id;
  import javax.persistence.Table;
  
  @Entity
  @Table(name="employetest")
  public class Employee {
  
   @Id
   @GeneratedValue
   private int id;
  
   @Column(name = "firstname")
   private String firstName;
  
   @Column(name = "lastname")
   private String lastName;
  
   @Column(name = "email")
   private String email;
  
   @Column(name = "phone")
   private String phone;
  
   public int getId() {
    return id;
   }
  
   public void setId(int id) {
    this.id = id;
   }
  
   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 String getEmail() {
    return email;
   }
  
   public void setEmail(String email) {
    this.email = email;
   }
  
   public String getPhone() {
    return phone;
   }
  
   public void setPhone(String phone) {
    this.phone = phone;
   }
  
  }
  </code></pre>
  
  <p>UserDao.java</p>
  
  <pre><code>package com.anzy.dao;
  
  import java.util.List;
  
  import com.anzy.domain.User;
  
  public interface UserDao
  {
      void addUser(User user);
      void editUser(User user);
      void deleteUser(int userId);
      User findUser(int useId);
      User findUserByName(String username);
      List&lt;User&gt; getAllUser();
  
  
  
  }
  </code></pre>
  
  <p>UserDaoImpl.java</p>
  
  <pre><code>package com.anzy.dao;
  
  import java.util.List;
  
  import org.hibernate.Criteria;
  import org.hibernate.SessionFactory;
  import org.hibernate.criterion.Restrictions;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.stereotype.Repository;
  
  import com.anzy.domain.User;
  @Repository
  public class UserDaoImpl implements UserDao
  {
      @Autowired
      private SessionFactory session;
  
      public void addUser(User user)
      {
          session.getCurrentSession().save(user);
  
      }
  
      public void editUser(User user) {
          session.getCurrentSession().update(user);
  
  
      }
  
      public void deleteUser(int userId) {
          session.getCurrentSession().delete(findUser(userId));
  
      }
  
      public User findUser(int userId) {
          return (User) session.getCurrentSession().get(User.class,userId);
      }
  
      public User findUserByName(String username) {
  Criteria criteria=session.getCurrentSession().createCriteria(User.class);
  criteria.add(Restrictions.eq("username", username));
          return (User)criteria.uniqueResult();
      }
  
      public List&lt;User&gt; getAllUser() {
          // TODO Auto-generated method stub
          return session.getCurrentSession().createQuery("from User").list();
      }
  
  }
  </code></pre>
  
  <p>UserDetailsServiceImpl.java</p>
  
  <pre><code>package com.anzy.services;
  
  import java.util.ArrayList;
  import java.util.Collection;
  
  import org.springframework.transaction.annotation.Transactional;
  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.UserDetails;
  import org.springframework.security.core.userdetails.UserDetailsService;
  import org.springframework.security.core.userdetails.UsernameNotFoundException;
  import org.springframework.stereotype.Service;
  import com.anzy.dao.UserDao;
  import com.anzy.domain.Role;
  import com.anzy.domain.User;
  import com.anzy.domain.UserStatus;
  @Service("userDetailsService")
  public class UserDetailsServiceImpl  implements UserDetailsService
  {
      @Autowired
      private UserDao userDao;
  
      @Transactional(readOnly=true)
      public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
      {
          User user=userDao.findUserByName(username);
          if(user!=null)
          {
              String password=user.getPassword();
              boolean enabled=user.getStatus().equals(UserStatus.ACTIVE);
              boolean accountNonExpired=user.getStatus().equals(UserStatus.ACTIVE);
              boolean credentialsNonExpired=user.getStatus().equals(UserStatus.ACTIVE);
              boolean accountNonLocked=user.getStatus().equals(UserStatus.ACTIVE);
              Collection &lt;GrantedAuthority&gt; authorities=new ArrayList&lt;GrantedAuthority&gt;();
          for(Role role:user.getRoles())
          {
              authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
          }
  org.springframework.security.core.userdetails.User secureUser=new org.springframework.security.core.userdetails.User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
      return secureUser;
          }
          else
          {
              throw new UsernameNotFoundException("User not found !!!"); 
  
          }
      }
  
  }
  </code></pre>
  
  <p>DataDao.java</p>
  
  <pre><code>package com.anzy.dao;
  
  import java.util.List;
  
  import com.anzy.domain.Employee;
  
  public interface DataDao 
  {
   public int insertRow(Employee employee);
  
   public List&lt;Employee&gt; getList();
  
   public Employee getRowById(int id);
  
   public int updateRow(Employee employee);
  
   public int deleteRow(int id);
  
  }
  </code></pre>
  
  <p>DataDaoImpl.java</p>
  
  <pre><code>package com.anzy.dao;
  
  import java.io.Serializable;
  import java.util.List;
  
  import javax.transaction.Transactional;
  
  import org.hibernate.Session;
  import org.hibernate.SessionFactory;
  import org.hibernate.Transaction;
  import org.springframework.beans.factory.annotation.Autowired;
  
  import com.anzy.domain.Employee;
  
  public class DataDaoImpl implements DataDao {
  
   @Autowired
   SessionFactory sessionFactory;
  
   @Transactional
   public int insertRow(Employee employee) {
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    session.saveOrUpdate(employee);
    tx.commit();
    Serializable id = session.getIdentifier(employee);
    session.close();
    return (Integer) id;
   }
  
   public List getList() {
    Session session = sessionFactory.openSession();
    @SuppressWarnings("unchecked")
    List employeeList = session.createQuery("from Employee")
      .list();
    session.close();
    return employeeList;
   }
  
   public Employee getRowById(int id) {
    Session session = sessionFactory.openSession();
    Employee employee = (Employee) session.load(Employee.class, id);
    System.out.println(employee);
    return employee;
   }
  
   public int updateRow(Employee employee) {
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    session.saveOrUpdate(employee);
    tx.commit();
    Serializable id = session.getIdentifier(employee);
    session.close();
    return (Integer) id;
   }
  
   public int deleteRow(int id) {
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    Employee employee = (Employee) session.load(Employee.class, id);
    session.delete(employee);
    tx.commit();
    Serializable ids = session.getIdentifier(employee);
    session.close();
    return (Integer) ids;
   }
  
  }
  </code></pre>
  
  <p>spring-config.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:context="http://www.springframework.org/schema/context"
   xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"&gt;
      &lt;context:component-scan base-package="com.anzy" /&gt;
      &lt;context:property-placeholder location="classpath:database.properties" /&gt;
      &lt;mvc:annotation-driven /&gt;
      &lt;bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"&gt;
          &lt;property name="driverClassName" value="${database.driver}" /&gt;
          &lt;property name="url" value="${database.url}" /&gt;
          &lt;property name="username" value="${database.user}" /&gt;
          &lt;property name="password" value="${database.password}" /&gt;
          &lt;property name="initialSize" value="20" /&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="annotatedClasses"&gt;  
              &lt;list&gt;  
                  &lt;value&gt;com.anzy.domain.Employee&lt;/value&gt;  
              &lt;/list&gt;  
          &lt;/property&gt; 
          &lt;property name="hibernateProperties"&gt;
              &lt;props&gt;
                  &lt;prop key="hibernate.dialect"&gt;${hibernate.dialect}&lt;/prop&gt;
                  &lt;prop key="hibernate.show_sql"&gt;${hibernate.show_sql}&lt;/prop&gt;
              &lt;/props&gt;
          &lt;/property&gt;
      &lt;/bean&gt;
  
      &lt;bean id="txManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager"&gt;
          &lt;property name="sessionFactory" ref="sessionFactory" /&gt;
      &lt;/bean&gt;
  
      &lt;bean id="persistenceExceptionTranslationPostProcessor"
          class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /&gt;
  
      &lt;bean
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt;
          &lt;property name="prefix"&gt;
              &lt;value&gt;/WEB-INF/pages/&lt;/value&gt;
          &lt;/property&gt;
          &lt;property name="suffix"&gt;
              &lt;value&gt;.jsp&lt;/value&gt;
          &lt;/property&gt;
      &lt;/bean&gt;
      &lt;bean id="dataDaoImpl" class="com.anzy.dao.DataDaoImpl" /&gt;
  
  &lt;!--    &lt;bean id="dataServiceImpl" class="com.beingjavaguys.services.DataServiceImpl" /&gt;
   --&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"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/security
          http://www.springframework.org/schema/security/spring-security.xsd"&gt;
  
  &lt;http auto-config="true"&gt;
      &lt;intercept-url pattern="/*" access="isAuthenticated()"/&gt;
          &lt;form-login /&gt;
  &lt;!--         &lt;logout invalidate-session="true" /&gt;
   --&gt;    &lt;/http&gt;
  
      &lt;!-- &lt;authentication-manager&gt;
          &lt;authentication-provider&gt;
              &lt;user-service&gt;
                  &lt;user name="joseph" password="bagnes" authorities="Admin,User" /&gt;
                  &lt;user name="bernabe" password="jose" authorities="User" /&gt;
              &lt;/user-service&gt;
          &lt;/authentication-provider&gt;
      &lt;/authentication-manager&gt; --&gt;
  
      &lt;beans:bean id="daoAuthenticationProvider" class="  org.springframework.security.authentication.dao.DaoAuthenticationProvider"&gt;
      &lt;beans:property name="userDetailsService" ref="userDetailsService"&gt;&lt;/beans:property&gt;
      &lt;/beans:bean&gt;
  
      &lt;beans:bean id="authenticationManager" class="org.springframework.security.authentication.AuthenticationProvider"&gt;
          &lt;beans:property name="providers"&gt;
          &lt;beans:list&gt;
          &lt;beans:ref local="daoAuthenticationProvider"/&gt;
          &lt;/beans:list&gt;
          &lt;/beans:property&gt;
      &lt;/beans:bean&gt;
      &lt;authentication-manager&gt;
      &lt;authentication-provider user-service-ref="userDetailsService"&gt;
      &lt;password-encoder hash="md5"&gt;&lt;/password-encoder&gt;
      &lt;/authentication-provider&gt;
      &lt;/authentication-manager&gt; 
  
  &lt;/beans:beans&gt;
  </code></pre>
  
  <p>web.xml</p>
  
  <pre><code>&lt;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_2_5.xsd"
      version="2.5"&gt;
  
      &lt;display-name&gt;Sample Spring Maven Project&lt;/display-name&gt;
      &lt;servlet&gt;
          &lt;servlet-name&gt;mvc-dispatcher&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;/WEB-INF/spring-config.xml&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;mvc-dispatcher&lt;/servlet-name&gt;
          &lt;url-pattern&gt;/&lt;/url-pattern&gt;
      &lt;/servlet-mapping&gt;
      &lt;context-param&gt;
          &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
          &lt;param-value&gt;
              /WEB-INF/spring-security.xml
          &lt;/param-value&gt;
      &lt;/context-param&gt;
      &lt;filter&gt;
          &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
          &lt;filter-class&gt;org.springframework.web.filter.DelegatingFilterProxy&lt;/filter-class&gt;
      &lt;/filter&gt;
      &lt;filter-mapping&gt;
          &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
          &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
      &lt;/filter-mapping&gt;
      &lt;listener&gt;
          &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
      &lt;/listener&gt;
      &lt;listener&gt;
          &lt;listener-class&gt;org.springframework.security.web.session.HttpSessionEventPublisher&lt;/listener-class&gt;
      &lt;/listener&gt;
  
  &lt;/web-app&gt;
  </code></pre>