Almost Useless Top Tip for Today: Lombok @RequiredArgsConstructor

Wiring up Spring Components using @Autowired is convenient but makes testing harder. A better solution is passing dependencies in through a constructor. However, that means creating a constructor. Lombok to the rescue with the @AllArgsConstructor annotation which will create a constructor that requires all your Class variables. Great for most situations but what if you want only some variables initialised through the constructor? Use the @RequiredArgsConstructor and make your variables final.


@Component
@RequiredArgsConstructor
public class MyService {
private final MyFirstDependency firstDependency;
private final MySecondDependency secondDependency;

private MyThirdDependency optionalDependency;
}

This entry was posted in Programming and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *