Resolving Spring Security Null UserRepo with @Autowired in CustomUserDetailsService
Resolving Spring Security Null UserRepo with @Autowired in CustomUserDetailsService

UserRepo Is Null in CustomUserDetailsService Causing Authentication Failure

Fix Spring Security authentication errors caused by Null UserRepo in CustomUserDetailsService with proper @Autowired usage.6 min


When developing a Spring Boot application with Spring Security, encountering issues with authentication can quickly become frustrating. One common but easily overlooked issue is seeing your UserRepo turn up null in your CustomUserDetailsService, causing authentication to fail.

Typically, this problem manifests itself with the dreaded error message:

java.lang.NullPointerException: Cannot invoke 
"com.example.app.repositories.UserRepo.findByUsername(java.lang.String)" 
because "this.userRepo" is null

It’s definitely not fun to stumble upon this while testing your login functionality. But don’t worry—let’s break down exactly what’s happening here and how you can quickly troubleshoot and fix it.

Understanding the Core Issue: Why is UserRepo Null?

The root cause of this issue lies in how Spring handles @Autowired dependencies. The `@Autowired` annotation instructs Spring to inject dependencies automatically. Here, we rely on it to inject our repository (UserRepo) into various components like our CustomUserDetailsService class.

In our application, the UserRepo interface typically extends Spring Data JPA’s JpaRepository, providing abstraction over database operations. This repository includes critical methods like findByUsername(), crucial for authenticating users.

Analyzing the Error: Why a NullPointerException?

A NullPointerException occurs whenever you attempt to invoke a method on an object that is not initialized (is null). In our scenario, UserRepo is supposed to be injected via @Autowired, but the injection is failing silently, leaving it null. When authentication triggers code execution like this:

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepo.findByUsername(username);
    if (user == null) {
        throw new UsernameNotFoundException("User not found");
    }
    return new CustomUserDetails(user);
}

Since userRepo is null—not injected correctly—this leads directly to the NullPointerException.

Walking Through the Code & Identifying the Issue

Let’s quickly revisit the key parts of the application involved here.

The UserRepo Interface:

Typically, you’ll see something like this:

public interface UserRepo extends JpaRepository<User, Long> {
    User findByUsername(String username);
}

This repository needs automatic injection wherever it’s needed.

The SecurityConfig Class:

In your main security configuration, dependencies must be properly injected and beans well-defined. Suppose your SecurityConfig class looks somewhat similar to:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Autowired
    private CustomUserDetails customUserDetails;

    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeHttpRequests(auth -> 
                auth.anyRequest().authenticated()
            )
            .httpBasic();
        return http.build();
    }

    @Bean
    AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }
}

Look closely here—are you initializing your CustomUserDetailsService as a managed Bean correctly?

The SecurityBeans Class:

In Spring Security, bean configuration is critical. It’s common to create a SecurityBeans file explicitly defining Beans such as:

@Configuration
public class SecurityBeans {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsService userDetailsService(UserRepo userRepo) {
        return new CustomUserDetails(userRepo);
    }

    @Bean
    public AuthenticationProvider authenticationProvider(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setPasswordEncoder(passwordEncoder);
        provider.setUserDetailsService(userDetailsService);
        return provider;
    }
}

Make sure your UserDetailsService bean is properly configured and initialized here.

The CustomUserDetails Class:

CustomUserDetails handles user loading logic. It implements UserDetailsService:

@Service
public class CustomUserDetails implements UserDetailsService {

    private final UserRepo userRepo;

    @Autowired
    public CustomUserDetails(UserRepo userRepo) {
        this.userRepo = userRepo;
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        User user = userRepo.findByUsername(username);
        if(user == null){
            throw new UsernameNotFoundException("User Not Found");
        }
        return new CustomUserDetailsImpl(user); // assuming you have an impl
    }
}

Check closely if your CustomUserDetails constructor aligns properly with Bean injection logic.

Troubleshooting and Resolving the Issue

If you encounter the null UserRepo issue, perform these checks step by step:

  1. Check @Autowired annotation: Ensure it’s correctly placed on constructors, fields, or setters.
  2. Confirm Bean Creation: Verify beans are explicitly defined in your SecurityBeans or Config classes with proper annotations.
  3. Proper Configuration of CustomUserDetails: Confirm the constructor injection is correctly done, and no manual instantiation without dependency injection is occurring.

Some practical solutions include:

  • Reconfiguring your SecurityConfig to explicitly declare your CustomUserDetails bean where necessary.
  • Ensuring beans like UserRepo and CustomUserDetails are discovered by component scanning (confirm package scanning in your main Spring Boot Application class).
  • Using constructor-based injection instead of field-based @Autowired annotation, as recommended by Spring.

After troubleshooting and correcting these issues, your CustomUserDetailsService will properly receive the UserRepo instance.

Testing Your Fixes

After configuring properly, test your authentication logic again. Ensure proper behavior:

  • Verify successful login attempts.
  • Test user retrieval functions are operational from UserRepo.

Try integrating unit tests or mocks using Mockito to ensure automated verification of these scenarios.

Best Practices for Avoiding Null Pointer Issues with @Autowired

To prevent issues like this in the future, follow these simple but effective best practices:

  • Prefer constructor injection whenever possible.
  • Clearly define Bean declarations in configuration classes to maintain readability and clarity.
  • Use tools like Spring Boot DevTools and Lombok to simplify Bean initialization and dependency injection.

Understanding how Spring manages your beans and dependencies helps you avoid subtle configuration problems. It ensures your project continues running smoothly, especially crucial aspects like user authentication.

There you have it—a straightforward solution to your Spring Security authentication woes caused by a null UserRepo instance. Properly managed Beans and dependency injection can make your app more predictable, maintainable, and reliable.

Are you currently working through other dependency injection or Spring-related issues? Let us know in the comments—or explore other useful articles in our JavaScript category if you’re also exploring frontend frameworks and technologies.


Like it? Share with your friends!

Shivateja Keerthi
Hey there! I'm Shivateja Keerthi, a full-stack developer who loves diving deep into code, fixing tricky bugs, and figuring out why things break. I mainly work with JavaScript and Python, and I enjoy sharing everything I learn - especially about debugging, troubleshooting errors, and making development smoother. If you've ever struggled with weird bugs or just want to get better at coding, you're in the right place. Through my blog, I share tips, solutions, and insights to help you code smarter and debug faster. Let’s make coding less frustrating and more fun! My LinkedIn Follow Me on X

0 Comments

Your email address will not be published. Required fields are marked *