Lombok's copyableAnnotations for Spring

It is generally a good practise to declare the dependencies in a java class as final and inject the dependencies through the constructor.

With Lombok's @AllArgsConstructor and @RequiredArgsConstructor, the generated constructor has all the final fields as parameters.

However, if we use the @Qualifier and @Value for the final fields, then by default Lombok doesn't copy these annotation to the constructor parameters.

In order to apply/copy these annotations to the constructor parameters, the following lombok config is required.

Create lombok.config file in the route directory of the project and add the following lines

lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Value
This configuration inform Lombok to copy annotation applied at final field to constructor parameters.

Example:

Source Code

@Component
@AllArgsConstructor
public class SampleService {
@Qualifier("interfaceA")
private final SampleInterface sampleInterface;
@Value("${sample.string}")
private final String sampleStringValue;
}
Generated Source Code

@Component
public class SampleService {
@Qualifier("interfaceA")
private final SampleInterface sampleInterface;
@Value("${sample.string}")
private final String sampleStringValue;

public SampleService(
        @Qualifier("interfaceA") final SampleInterface sampleInterface, 
        @Value("${sample.string}") final String sampleStringValue) {
this.sampleInterface = sampleInterface;
this.sampleStringValue = sampleStringValue;
}
}

For older version of Spring (less than 4.3), if we have to add @Autowired annotation to the generated constructor, then source code as

@Component
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class SampleService {
@Qualifier("interfaceA")
private final SampleInterface sampleInterface;
@Value("${sample.string}")
private final String sampleStringValue;
}
Generated source code is

@Component
public class SampleService {
@Qualifier("interfaceA")
private final SampleInterface sampleInterface;
@Value("${sample.string}")
private final String sampleStringValue;

@Autowired
public SampleService(
        @Qualifier("interfaceA") final SampleInterface sampleInterface, 
        @Value("${sample.string}") final String sampleStringValue) {
this.sampleInterface = sampleInterface;
this.sampleStringValue = sampleStringValue;
}
}

Comments

Popular posts from this blog

JSON with curl and jq

Import self signed in Linux for Chrome / Chromium headless testing

Colima - Drop In replacement for Docker Desktop for Mac and Linux