Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 755
runnerpaul Avatar asked Nov 21 '25 06:11

runnerpaul


2 Answers

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>             
like image 181
Đorđe Stanković Avatar answered Nov 22 '25 19:11

Đorđe Stanković


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.

like image 44
Shekhar Rai Avatar answered Nov 22 '25 21:11

Shekhar Rai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!