Skip to content

Instantly share code, notes, and snippets.

@odrotbohm
Last active November 3, 2020 08:22
Show Gist options
  • Save odrotbohm/5896044 to your computer and use it in GitHub Desktop.
Save odrotbohm/5896044 to your computer and use it in GitHub Desktop.
Constructor injection example with Lombok
/**
* Sample component implementation showing the usage of constructor injection
* avoiding the need to declare a constructor by the help of Lombok. There are
* several advantages of using constructor injection over field injection:
*
* <ol>
* <li>The class communicates its dependencies. Just start with {@code new
* MyDependencyImpl(…}and your IDE will tell you what you need to hand it in. No
* need to look into the implementation of the class to discover that.</li>
* <li>The class can only be used in valid state. The constructor argument require
* the creator to pass in arguments. Using {@code NonNull} even prevents an accidental
* {@literal null} being passed in. So no {@code new MyComponentImpl().someMethod()}
* throwing a {@code NullPointerException} because of a missing dependency.</li>
* </ol>
*
* @see http://www.projectlombok.org
*/
@RequiredArgsConstructor(onConstructor = @__(@Inject))
class MyComponentImpl implements MyComponent {
private final @NonNull MyDependency first;
private final @NonNull MyOtherDependency second;
private final @NonNull YetAnotherDependency third;
// methods
}
@chaoyangnz
Copy link

not working Java 11

@odrotbohm
Copy link
Author

I've updated the gist to rather use the @__ variant. Note, that you don't need any annotation whatsoever to let e.g. Spring instantiate the component properly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment