CodexBloom - Programming Q&A Platform

Unexpected NullPointerException in Spring Boot Application using Java 17 with Lombok

👀 Views: 62 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-07
java spring-boot lombok Java

I'm a bit lost with I'm facing a `NullPointerException` in my Spring Boot application when I try to access a field that I expected to be initialized by Lombok's `@NonNull`. The model looks like this: ```java import lombok.NonNull; import lombok.Data; @Data public class User { @NonNull private String username; private String email; } ``` In my service, I'm trying to create a new `User` object like this: ```java @Service public class UserService { public void createUser(String username) { User user = new User(); // No email provided user.setUsername(username); // Here, I expect username to be non-null, but... System.out.println(user.getUsername().length()); // This throws NullPointerException } } ``` I've ensured that the `username` parameter passed to `createUser` is not null. However, the stack trace indicates that the exception is thrown when trying to access the length of `username`. I've tried adding `@Builder` to my `User` class, but it doesn't change the outcome. Is there something I'm missing in my configuration or usage of Lombok? I am using Lombok version `1.18.24` with Spring Boot version `2.7.4`. My team is using Java for this microservice. What's the correct way to implement this?