title: Spring security from xml configuration to java config
body: <p>This was my security xml configuration.</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;csrf disabled="true"/&gt;
          &lt;intercept-url pattern="/" access="hasRole('ROLE_USER')"/&gt;
          &lt;intercept-url pattern="/welcome" access="hasRole('ROLE_USER')"/&gt;
          &lt;form-login login-page="/login" default-target-url="/welcome" authentication-failure-url="/login?error"
                      username-parameter="username" password-parameter="password"/&gt;
          &lt;logout logout-success-url="/login?logout"/&gt;
      &lt;/http&gt;
  
      &lt;authentication-manager alias="authenticationManager"&gt;
          &lt;authentication-provider user-service-ref="userDetailsServiceImpl"&gt;
              &lt;password-encoder ref="encoder"/&gt;
          &lt;/authentication-provider&gt;
      &lt;/authentication-manager&gt;
  
      &lt;beans:bean id="userDetailsServiceImpl" class="com.egs.account.service.user.UserDetailsServiceImpl"/&gt;
  
      &lt;beans:bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"&gt;
          &lt;beans:constructor-arg name="strength" value="11"/&gt;
      &lt;/beans:bean&gt;
  &lt;/beans:beans&gt;
  </code></pre>
  
  <p>And this one was my web.xml file.</p>
  
  <pre><code>&lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns="http://java.sun.com/xml/ns/javaee"
           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;Account Registration Web Application&lt;/display-name&gt;
  
      &lt;context-param&gt;
          &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
          &lt;param-value&gt;/resources/appconfig-root.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;servlet&gt;
          &lt;servlet-name&gt;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;
          &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;dispatcher&lt;/servlet-name&gt;
          &lt;url-pattern&gt;/&lt;/url-pattern&gt;
      &lt;/servlet-mapping&gt;
  
      &lt;listener&gt;
          &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
      &lt;/listener&gt;
  &lt;/web-app&gt;
  </code></pre>
  
  <p>Now I have switched to Java config, and those Config classes are the equivalent versions of my web.xml and security.xml files.</p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  @ComponentScan("com.egs.account.*")
  @EnableGlobalMethodSecurity(prePostEnabled = true)
  public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  
      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
          auth.authenticationProvider(authProvider())
                  .inMemoryAuthentication()
                  .withUser("user").password("password").roles("USER");
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
  
          http.authorizeRequests()
                  .antMatchers("/").permitAll()
                  .antMatchers("/welcome**").access("hasRole('USER')")
                  .and().formLogin()
                  .loginPage("/login")
                  .defaultSuccessUrl("/welcome")
                  .failureUrl("/login?error");
  
          http.csrf().disable();
      }
  
      @Autowired
      public DaoAuthenticationProvider authProvider() {
          DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
          authProvider.setUserDetailsService(userDetailsServiceImpl());
          authProvider.setPasswordEncoder(bCryptPasswordEncoder());
  
          return authProvider;
      }
  
      @Bean
      public PasswordEncoder bCryptPasswordEncoder() {
          return new BCryptPasswordEncoder(11);
      }
  
      @Autowired
      public UserDetailsService userDetailsServiceImpl() {
          return new UserDetailsServiceImpl();
      }
  }
  
  public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
  
      public SecurityWebApplicationInitializer() {
          super(SecurityConfiguration.class);
      }
  
  }
  
  
  @Configuration
  @PropertySource(value = "classpath:application.properties")
  @ComponentScan(basePackages = {"com.egs.account.*"})
  @Import({SecurityConfiguration.class, MvcConfig.class})
  public class SpringWebAppInitializer implements WebApplicationInitializer {
  
      @Autowired
      Environment env;
  
      @Override
      public void onStartup(ServletContext servletContext) throws ServletException {
          AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
          appContext.register(MvcConfig.class);
          appContext.setServletContext(servletContext);
          ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
                  "dispatcher", new DispatcherServlet(appContext));
          dispatcher.setLoadOnStartup(1);
          dispatcher.addMapping("/");
      }
  
      @Bean
      public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
          return new PropertySourcesPlaceholderConfigurer();
      }
  }
  </code></pre>
  
  <p>And when I run the application, I get such exception.</p>
  
  <pre><code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'securityService': Error creating bean with name 'securityServiceImpl': Unsatisfied dependency expressed through field 'authenticationManager': No qualifying bean of type [org.springframework.security.authentication.AuthenticationManager] found for dependency [org.springframework.security.authentication.AuthenticationManager]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.authentication.AuthenticationManager] found for dependency [org.springframework.security.authentication.AuthenticationManager]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityServiceImpl': Unsatisfied dependency expressed through field 'authenticationManager': No qualifying bean of type [org.springframework.security.authentication.AuthenticationManager] found for dependency [org.springframework.security.authentication.AuthenticationManager]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.authentication.AuthenticationManager] found for dependency [org.springframework.security.authentication.AuthenticationManager]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
  </code></pre>
  
  <p>This part of my UserController.</p>
  
  <pre><code>@Controller
  public class UserController {
  
      private UserService userService;
  
      @Autowired
      private CatalogService catalogService;
  
      @Autowired
      private SecurityService securityService;
  }
  </code></pre>
  
  <p>And this one is my SecurityServiceImpl</p>
  
  <pre><code>@Service("securityServiceImpl")
  public class SecurityServiceImpl implements SecurityService {
  
      @Autowired
      private AuthenticationManager authenticationManager;
  
      @Autowired
      private UserDetailsService userDetailsService;
  
      private static final Logger logger = LoggerFactory.getLogger(SecurityServiceImpl.class);
  
      @Override
      public String findLoggedInUsername() {
          Object userDetails = SecurityContextHolder.getContext().getAuthentication().getDetails();
          if (userDetails instanceof UserDetails) {
              return ((UserDetails) userDetails).getUsername();
          }
  
          return null;
      }
  
      @Override
      public void autoLogin(String username, String password) {
          UserDetails userDetails = userDetailsService.loadUserByUsername(username);
          UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                  new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
  
          authenticationManager.authenticate(usernamePasswordAuthenticationToken);
  
          if (usernamePasswordAuthenticationToken.isAuthenticated()) {
              SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
              logger.debug(String.format("Auto login %s successfully!", username));
          }
      }
  }
  </code></pre>
  
  <p>Who can tell me what else I have forgotten to add, as I got such terrible exception.</p>