title: How to configure Spring-Security to access user details in database?
body: <p>I am puzzled with SpringSecurity. There are many ways to implement a simple thing and I mixed them all up. </p>
  
  <p>My code is as follows but it throws exception. If I remove <code>UserDetailsService</code> related codes, the application runs and I can login <code>in-memory</code> users. As suggested below, I converted the configuration to XML based but users cannot sign-in.</p>
  
  <pre><code>org.springframework.beans.factory.BeanCreationException: Error creating bean 
  with name 'securityConfig': Injection of autowired dependencies failed; nested 
  exception is org.springframework.beans.factory.BeanCreationException: Could 
  not autowire field:  
  org.springframework.security.core.userdetails.UserDetailsService 
  com.myproj.config.SecurityConfig.userDetailsService; nested exception is 
  org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying 
  bean of type    
  [org.springframework.security.core.userdetails.UserDetailsService] found for 
  dependency: expected at least 1 bean which qualifies as autowire candidate for 
  this dependency. Dependency annotations: 
  {@org.springframework.beans.factory.annotation.Autowired(required=true),  
  @org.springframework.beans.factory.annotation.Qualifier(value=userDetailsService)}
  
  Caused by: org.springframework.beans.factory.BeanCreationException: Could not 
  autowire field 
  
  org.springframework.security.core.userdetails.UserDetailsService 
  com.myproj.config.SecurityConfig.userDetailsService; nested exception is 
  org.springframework.beans.factory.NoSuchBeanDefinitionException: 
  No qualifying bean of type 
  [org.springframework.security.core.userdetails.UserDetailsService] 
  found for dependency: expected at least 1 bean which qualifies as autowire 
  candidate for this dependency. Dependency annotations: 
  {@org.springframework.beans.factory.annotation.Autowired(required=true), 
  @org.springframework.beans.factory.annotation.Qualifier(value=userDetailsService)}
  
  Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: 
  No qualifying bean of type 
  [org.springframework.security.core.userdetails.UserDetailsService] found for 
  dependency: expected at least 1 bean which qualifies as autowire candidate for 
  this dependency. Dependency annotations: 
  {@org.springframework.beans.factory.annotation.Autowired(required=true), 
  @org.springframework.beans.factory.annotation.Qualifier(value=userDetailsService)}
  </code></pre>
  
  <p><strong>Web.xml</strong></p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &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_3_0.xsd"
      version="3.0"&gt;
      &lt;listener&gt;
          &lt;listener-class&gt;org.apache.tiles.extras.complete.CompleteAutoloadTilesListener&lt;/listener-class&gt;
      &lt;/listener&gt;
  
      &lt;servlet&gt;
          &lt;servlet-name&gt;proj&lt;/servlet-name&gt;
          &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
          &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
      &lt;/servlet&gt;
  
      &lt;servlet-mapping&gt;
        &lt;servlet-name&gt;proj&lt;/servlet-name&gt;
        &lt;url-pattern&gt;/&lt;/url-pattern&gt;
      &lt;/servlet-mapping&gt;
  
  
  
  &lt;/web-app&gt;
  </code></pre>
  
  <p><strong>MvcWebApplicationInitializer</strong></p>
  
  <pre><code>import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
  
  
  public class MvcWebApplicationInitializer
      extends AbstractAnnotationConfigDispatcherServletInitializer {
  
      @Override
      protected Class&lt;?&gt;[] getRootConfigClasses() {
          return new Class[] { SecurityConfig.class };
      }
  
      @Override
      protected Class&lt;?&gt;[] getServletConfigClasses() {
          return null;
      }
  
      @Override
      protected String[] getServletMappings() {
          return new String[] { "/" };
      }
  
  }
  </code></pre>
  
  <p><strong>SecurityWebApplicationInitializer</strong></p>
  
  <pre><code>import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
  
  public class SecurityWebApplicationInitializer
  extends AbstractSecurityWebApplicationInitializer {
  
  }
  </code></pre>
  
  <p><strong>SecurityConfig</strong></p>
  
  <pre><code>@Configuration
  @EnableWebMvcSecurity
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
  
      @Autowired
      @Qualifier("userDetailsService")
      UserDetailsService userDetailsService;
  
      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder auth)
              throws Exception {
          auth.userDetailsService(userDetailsService).passwordEncoder(
                  passwordEncoder());
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.authorizeRequests()
                  .antMatchers("/resources/**", "/", "/index", "/aboutus")
                  .permitAll()
                  .antMatchers("/profile/**")
                  .hasRole("USER")
                  .and()
                  .formLogin().loginPage("/signin").failureUrl("/signin?error")
                  .permitAll().and().logout().logoutUrl("/signout").permitAll();
  
      }
  
      @Bean
      public PasswordEncoder passwordEncoder() {
          PasswordEncoder encoder = new BCryptPasswordEncoder();
          return encoder;
      }
  
      @Bean
      @Override
      public AuthenticationManager authenticationManagerBean() throws Exception        
      {
          return super.authenticationManagerBean();
      }
  
  }
  </code></pre>
  
  <p><strong>MemberServiceImpl</strong></p>
  
  <pre><code>@Service("userDetailsService")
  public class MemberServiceImpl implements UserDetailsService {
  
      @Autowired
      MemberRepository memberRepository;
  
      private List&lt;GrantedAuthority&gt; buildUserAuthority(String role) {
          Set&lt;GrantedAuthority&gt; setAuths = new HashSet&lt;GrantedAuthority&gt;();
          setAuths.add(new SimpleGrantedAuthority(role));
          List&lt;GrantedAuthority&gt; result = new ArrayList&lt;GrantedAuthority&gt;(
                  setAuths);
          return result;
      }
  
      private User buildUserForAuthentication(Member member,
              List&lt;GrantedAuthority&gt; authorities) {
          return new User(member.getEmail(), member.getPassword(),
                  member.isEnabled(), true, true, true, authorities);
      }
  
      @Override
      @Transactional(readOnly = true)
      public UserDetails loadUserByUsername(String username)
              throws UsernameNotFoundException {
          Member member = memberRepository.findByUserName(username);
          List&lt;GrantedAuthority&gt; authorities = buildUserAuthority("Role");
          return buildUserForAuthentication(member, authorities);
      }
  
  }
  </code></pre>
  
  <p><strong>Update 1</strong></p>
  
  <p>Even after adding following annotation, and <code>authenticationManagerBean</code> method from SecurityConfig the same exception is being thrown.</p>
  
  <pre><code>    @EnableGlobalMethodSecurity(prePostEnabled = true)
  </code></pre>
  
  <p><strong>Update 2</strong></p>
  
  <p>As suggested in one of the answers, I converted it to XML based configuration, the current code is as following;however, when I submit login form it does not do anything.</p>
  
  <p><strong>Spring-Security.xml</strong></p>
  
  <pre><code>&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-3.0.xsd"&gt;
  
  
  
      &lt;beans:import resource='login-service.xml' /&gt;
      &lt;http auto-config="true" access-denied-page="/notFound.jsp"
          use-expressions="true"&gt;
          &lt;intercept-url pattern="/" access="permitAll" /&gt;
  
  
          &lt;form-login login-page="/signin" authentication-failure-url="/signin?error=1"
              default-target-url="/index" /&gt;
          &lt;remember-me /&gt;
          &lt;logout logout-success-url="/index.jsp" /&gt;
      &lt;/http&gt;
      &lt;authentication-manager&gt;
          &lt;authentication-provider&gt;
              &lt;!-- &lt;user-service&gt; &lt;user name="admin" password="secret" authorities="ROLE_ADMIN"/&gt; 
                  &lt;user name="user" password="secret" authorities="ROLE_USER"/&gt; &lt;/user-service&gt; --&gt;
              &lt;jdbc-user-service data-source-ref="dataSource"
  
                  users-by-username-query="
                select username,password,enabled 
                from Member where username=?"
  
                  authorities-by-username-query="
                        select username 
                        from Member where username = ?" /&gt;
          &lt;/authentication-provider&gt;
      &lt;/authentication-manager&gt;
  &lt;/beans:beans&gt;
  </code></pre>
  
  <p><strong>login-service.xml</strong></p>
  
  <pre><code>&lt;beans xmlns="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"&gt;
  
     &lt;bean id="dataSource"
      class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;
  
      &lt;property name="driverClassName" value="com.mysql.jdbc.Driver" /&gt;
      &lt;property name="url" value="jdbc:mysql://localhost/testProject" /&gt;
      &lt;property name="username" value="root" /&gt;
      &lt;property name="password" value="" /&gt;
     &lt;/bean&gt;
  
  &lt;/beans&gt;
  </code></pre>