Inject

Guice provides the @Inject annotation to indicate that a consumer is dependent on a particular dependency. The injector takes care of initializing this dependency using the object graph. Guice gets a hint from the annotation that it needs to participate in the class construction phase. The @Inject annotation can be utilized in a constructor for a class, for a method, or for a field. Consider the following code:

//Field level injection@Injectprivate NotificationService notificationService;//Constructor level Injection@Injectpublic AppConsumer(NotificationService service){     this.notificationService=service;}//Method  level injection@Injectpublic void setService(NotificationService service) {    this.notificationService = service;}

Get Java 9 Dependency Injection now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.