javaspring-bootconstructorlombokdefault-constructor

Variable not initialized in default constructor


I have this class:

import lombok.Data;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

// tag::code[]
@Data
@Document
public class Image {

    @Id final private String id;
    final private String name;
}
// end::code[]

My understanding is that @Data should create a constructor for all final fields by default. However when I run my application I get this error:

error: variable id not initialized in the default constructor
        @Id final private String id;

Why would this be happening?


Solution

  • My understanding is that @Data should create a constructor for all final fields by default. Error: variable id not initialized in the default constructor @Id final private String id; Why would this be happening?

    Yes! you are right! @Data annotation generates a parameterized constructor for final fields, generates setters for all non-final fields and getters for both types of fields.

    In your case, your generated constructor should look like this,

    public Image(Long id, String name) {
        this.id = id;
        this.name = name;
    }
    
    //getters for both fields
    

    As your constructor not able to initialize the final fields - seems Lombok is not being set up properly - you can verify it by checking your Image.class in the target/classes directory with the same package(as you have it in your src except you have defined the location explicitly through config file). If it's not being generated, verify your dependency, Lombok plugin, you may want to explore Lombok configuration for further set-up.