Guice injection
As we know what dependency injection is, let us explore how Google Guice provides injection.
We have seen that the injector helps to resolve dependencies by reading configurations from modules, which are called bindings. Injector is preparing charts for the requested objects.
Dependency injection is managed by injectors using various types of injection:
- Constructor injection
- Method injection
- Field injection
- Optional injection
- Static injection
Constructor Injection
Constructor injection can be achieved by using the @Inject
annotation at the constructor level. This constructor ought to acknowledge class dependencies as arguments. Multiple constructors will, at that point, assign the arguments to their final fields:
public class AppConsumer { private NotificationService notificationService; //Constructor level Injection @Inject public AppConsumer(NotificationService service){ this.notificationService=service; } public boolean sendNotification(String message, String...