1. Configure Module to Enable the Dependency Injection Create SampleModule.java which extends AbstractModule. Abstract Module have configure () method which we need to override. Inside the configure() method need to define the Binding between the Interface and Corresponding Implementation as shown in the below example.
2. Interfaces and Implementation As shown in the above point we need to Create the Interface and Corresponding Implementation. For Example, JSMClient and RESTClient are the type of Client which can access the Service ( JMSService / RESTService). Client.java JMSClient.java is an Implementation of Interface Client.java. In the Above Example you can see different types of Injection which Google Guice Supports - i. Member Variable Injection – It’s responsibility of Guice to Inject the instance of member variable, as defined in configure() of SampleModule. Note - Can’t use Member variable inside the Constructor. ii. Constructor Based Injection – Inject Member variable using the Constructor. Either the Class should have default constructor or need to apply @Inject Annotation on the Constructor. iii. Setter Method based Injection – Need to apply @Inject Annotation on setter method, which Guice use to Inject the Variable. Any or All of the above injection type can be used at a time.
3. Services and Implementation Below defined as JMSService and JMSServiceImpl. In the Above example we have used annotation @Singleton which denotes that only instance will be created for Above mentioned service by Guice Framework. It Implements Singleton Design Pattern using Guice.
4. MainApplication / User Interface In the Main application, Guice Inject the instance of Client which has been bind in SampleModule using bind() and to().
5. Entry Point of Application In the Above mentioned way we can get the instance of Injector from the sameple Module. We can get the Instance of any class defined in the project using the Injector with condition either have a Default Constructor or Parameterized constructor with @Inject annotation.
6. How to Write JUnit test cases for Google Guice To Write the test case for functionalities using Guice, we need to Create the instance of Injector using the Module. We can Install the SampleModule which we had created. Need to Bind the necessary services, interface and implementation and install the existing module( If Necessary). Following is the example to show case – Output ----------- Inside the Main Application... Access Client.... Executing JMS Service ---------------------------------- User can run the Application either using test case MainApplicationTest.java or TestMainApplication.java. This post is written by
Soumitra Pathak - Linkedin, Facebook
He is a freelance writer, loves to explore latest features in Java technology.