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?
I had the same issue and it appears I haven't added the annotationProcessorPath to lombok during it's installation, similar to what @runnerpaul mentioned.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With