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...
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.
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).
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.
@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.
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
}
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