title: Spring boot @Autowired repository instance null when using spring security
body: <p><strong>My situation is this:</strong></p>
  
  <p>I am building a spring boot application, when I autowire the UserRepository in the controller it initializes it and when I try to call the findByUserName method everything is OK.</p>
  
  <p><strong>UserController</strong> </p>
  
  <pre><code>@Controller    
  @RequestMapping(path="/api/v1/users") 
  public class UserController {
  
  @Autowired 
  private UserRepository userRepository;
  
  @GetMapping(path="/{userName}")
  public @ResponseBody AuthenticationDetails getUserByUsername(@PathVariable String userName) throws UserNotFoundException {
  
      User user = userRepository.findByUserName(userName);=
      ...
      }
  }
  </code></pre>
  
  <p>After creating the controller I needed to use Spring Security to secure the paths of the controller so I added in the SecurityConfig class the following configuration:</p>
  
  <p><strong>SecurityConfig</strong></p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
  
  @Override
  public void configure(HttpSecurity httpSecurity) throws Exception {
      httpSecurity.csrf().disable().authorizeRequests()
              .antMatchers(HttpMethod.POST, "/login").permitAll().anyRequest().authenticated().and()
              .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()),
                      UsernamePasswordAuthenticationFilter.class)
              .addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
  
  }
  ...
  }
  </code></pre>
  
  <p>Now, when I try to post a request to the /login path I get a NullPointerException in the CustomAuthenticationProvider class when I try to load the data through userRepository instance by calling the findByUserName method because userRepository instance is null.</p>
  
  <p><strong>CustomAuthenticationProvider</strong></p>
  
  <pre><code>public class CustomAuthenticationProvider implements AuthenticationProvider {
  
  @Autowired 
  private UserRepository userRepository;
  
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  
      User userFromRepository = userRepository.findByUserName(authentication.getName().toLowerCase()); 
      ...
  }
  </code></pre>
  
  <p><strong>My questions are this:</strong></p>
  
  <p>Is not the state of the beans the same during the run-time of the application? Are the beans created when the application loads right? </p>
  
  <p><strong>Why Spring Boot manages to autowire the instance with the bean in my controller and in the same application but in another class it does not autowire them?</strong></p>