Search code examples
javaspring-bootspring-security-oauth2lombok

Lombok: RequiredArgsConstructor giving error while generating Constructor


It seems that @RequiredArgsConstructor not working in the code below.It throws error when I generate constructor . Why is it?

 import lombok.Data;
    import lombok.NonNull;
    import lombok.RequiredArgsConstructor;
    /**
     * Login response object containing the JWT
     **/
    @Data
    @RequiredArgsConstructor
    public class LoginResult {
        
        @NonNull
        private  String jwt;
    
        public LoginResult(String jwt) {
            this.jwt = jwt;
        }
    }

Dependency added in maven is

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
        <scope>provided</scope>
</dependency>

Error is - Duplicate method LoginResult(String) in type LoginResult


Solution

  • As you are using Lombok's @RequiredArgsConstructor which generates a constructor with 1 parameter for each field that requires special handling. In your case @NonNull on jwt field is saying jwt field needs special handling (a null check basically). Now lombok have added a constructor and even you have added a constructor and hence the error. Duplicate method LoginResult(String) in type LoginResult

    You can find more infomation about it on the following page https://projectlombok.org/features/constructor. (Adding screenshot in case it changes in future)

    enter image description here

    Solution: Remove your constructor and let Lombok do the magic