Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lombok does not generate RequiredArgsConstructor and AllArgsConstructor

I am using Lombok 1.16.18 and Gradle 4.0 with Java 8 and Spring-Boot 1.5.9.RELEASE.

When I build and run the project it succeeds, but when calling services which include Autowiring it fails with NullPointerException using @RequiredArgsConstructor(onConstructor = @__(@Autowired)) or @AllArgsConstructor(onConstructor = @__(@Autowired)).

I have checked the generated .classes and they are missing the constructors.

Of course if I create the constructors by hand and put @Autowire on it it works. But I am working on a big project with a lot of existing code, and don't want to rewrite everything. Any ideas on why this could happen? It looks like gradle or lombok is not preprocessing these annotations, however all the other @Getter and @Setter etc. are working fine and the generated .class files contain them...

like image 772
godzsa Avatar asked Jan 23 '19 14:01

godzsa


People also ask

How do you use Lombok AllArgsConstructor?

The @AllArgsConstructor annotation generates a constructor with one parameter for every field in the class. Fields that are annotated with @NonNull result in null checks with the corresponding parameters in the constructor. The annotation won't generate a parameter for the static and initialized final fields.

Can we use AllArgsConstructor and NoArgsConstructor together?

This is why you need to add @NoArgsConstructor annotation if you add the @AllArgsConstructor annotation. Also note that you are using @Data , which bundles the features of @RequiredArgsConstructor , which will generate a constructor for all final or @NonNull annotated fields (see Lombok documentation).

Does Lombok create constructor?

With Lombok, it's possible to generate a constructor for either all class's fields (with @AllArgsConstructor) or all final class's fields (with @RequiredArgsConstructor). Moreover, if you still need an empty constructor, you can append an additional @NoArgsConstructor annotation.

What is the difference between @data and @value in Lombok?

@Value is the immutable variant of @Data ; all fields are made private and final by default, and setters are not generated. The class itself is also made final by default, because immutability is not something that can be forced onto a subclass.


1 Answers

I use constructor injection only defining @RequiredArgsConstructor with final member variables as follows (without using onConstructor)

@Repository
@Slf4j
@RequiredArgsConstructor
public class FieldRepository {

    private final DSLContext dsl;

    private final DataSource dataSource;

    //... dsl and datasource are correctly injected 

}
like image 99
ValerioMC Avatar answered Sep 29 '22 09:09

ValerioMC