Java @ Desk: Guice Injection | Java at your desk

How to Configure Google Guice Servlet For Web Application

How to Configure Google Guice Servlet For Web Application

As we have seen in our previous post how easy it is to configure the DI (Dependency Injection) using Google Guice. In this post we will see how we can take the advantage of Google Guice Servlet Module to integrate / setup Web Application.

Guice Servlet Module allows us to completely eliminate the web.xml from Web Application Project and configure Servlets / Filters using the Java Configuration File itself.

Benefits – Google Guice provides us Following benefits
1) Constructor Injection, Setter, Field/member variable Injection
2) Type Safe Configuration ( eliminate web.xml file)
3) Modularization.
4) Can Inject the objects like request, response, session, requestParameters inside the servlet using DI.
5) Can define the Scope like Request Scope/ Session Scope using Annotation
6) It’s easy to use and integrate and no need to change the existing file/ servlets /jsp etc.

You can download the required Google Guice API from Google-Guice-3.0.zip. You need to extract .zip file and add all .jar files in the build path / .classpath of the project.

Let’s see the Components –

1. Configure GuiceFilter in web.xml
Need to Add the GuiceFilter in web.xml. It tells ServletContainer to re-route all the request through GuiceFilter. The Good thing is that all the existing Servlets/ JSP/ Filters will continue to function as normal and we can migrate it later.
<filter>
    <filter-name>guiceFilter</filter-name>
    <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>guiceFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


2. Install a Servlet Module / Enable Google Guice Servlet Module

In Order to install Servlet Module, we need to take 3 steps –
i. Create a WebServletModule which Extends ServletModule
ii. Create ServletConfig which extends GuiceServletContextListener.
iii. Configure GuiceServletContextListener inside the web.xml

Let’s Create a WebServletModule - First, in Servlet Module we can specify the Servlet / Filters mapping which we use to define inside web.xml. we can think of it as replacement of web.xml with enabled Guice DI capability.
public class WebServletModule extends ServletModule {

 // Specify Mapping of Servlet to URL.
 
 @Override
 public void configureServlets(){
  serve("/abc.html").with(EntryServlet.class);
 }
 
}


ServletConfig – ServletConfig Extends GuiceServletContextListener. Here we need to define all the modules that we want to install. In order to enable the Google Servlet Module we need to install WebServletModule and to define the binding we can have WebAppModule.
public class ServletConfig extends GuiceServletContextListener  {

 Injector injector;
 // Create Injector
 @Override
 protected Injector getInjector() {
  injector = Guice.createInjector(getModules());
  return injector;
 }
 
 // List of Modules for the Project. 
 private List<Module> getModules(){
  List<Module> modulesList = new ArrayList<Module>();
  modulesList.add(new WebServletModule());
  modulesList.add(new WebAppModule());
  return modulesList;
 }
}


Just for Reference WebAppModule.java–
public class WebAppModule extends AbstractModule {

 @Override
 protected void configure() {
  bind(User.class); // Later we will see, Bind the User.java
 }
}


Configure Listener inside the Web.xml – In order to install the modules we need to make a entry to ServletConfig in web.xml.
<listener>
    <listener-class>com.java.desk.config.ServletConfig</listener-class>
</listener>


Now we are done with all the configuration. Lets Create the Some html files and Servlets to run web Application using Google Guice.






User Case Scenario – A User will provide UserName and Email as Input and after submitting the data will be able to see the processes output.

Let’s see the Components Involved –
1. Entry.html – Take a input as username and Email and a submit button.
<body>
 <center><br><br><br><br><br><br><br><br>
 <form action="abc.html" method="get">
  UserName : <input type="text" name="userName"/> <br/>
  Email : <input type="text" name="email"/><br>
  <input type="submit" value="Submit"/>
 </form>
 </center>
</body>


As you can see, after clicking on Submit it will call abc.html and abc.html has been mapped with EntryServlet.java in WebServletModule.java.
serve("/abc.html").with(EntryServlet.class);


Below is the much awaited EntryServlet.java
Note -
Servlet Should apply @Singleton annotation.
Instantiate Object using injector.getInstance(User.class); don’t use new operator

This servlet Instantiate the User Object and call the processRequest() of User. We have bind the User.java in WebAppModule.java.
public class WebAppModule extends AbstractModule {

 @Override
 protected void configure() {
  bind(User.class);
 }
}

@Singleton
public class EntryServlet extends HttpServlet {
 
 private static final long serialVersionUID = 1L;
    
 @Inject
 Injector injector; // Inject a Injector
 
 @Inject 
    public EntryServlet() {
        super();
    }

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
 User user = injector.getInstance(User.class); //Need to Create the Instance using this method.
  user.processRequest();
  PrintWriter out = response.getWriter(); // Renders response over UI.
  String responseString = "After Processing"+"\n"+"Name = "+user.getName()+"\n"+"Email  = "+user.getEmail();
  out.print(responseString);
 }
}


Finally User.Java - Just to Keep it simple I have kept all objects inside one class only.
Now you can see, Since we have enabled Guice Servlet Module inside this web Application, I am able to inject request, response, session and requestParameters in User.java.
It’s quite easy to use and handle. Inside the process methods I fetched all the parameters passed from UI and set it into the UserObject itself.

@RequestScoped
public class User {
 
 @Inject
 @RequestParameters
 private Map<String, String[]> parameters;
 
 @Inject
 private HttpSession session;
 
 @Inject
 private ServletRequest request;
 
 @Inject
 private ServletResponse response;
 
 private String name;
 
 private String email;
 
 
public String getName() {
  return name;
 }

 
public void setName(String name) {
  this.name = name;
 }

 
public String getEmail() {
  return email;
 }

 
public void setEmail(String email) {
  this.email = email;
 }

 public String processRequest(){
  System.out.println("Enrty Servlet");
  
  String name = ((String[])parameters.get("userName"))[0];
  String email = ((String[])parameters.get("email"))[0];
  
  System.out.println("name "+name+" Email "+email);
  
  session.setAttribute("name",name);
  session.setAttribute("email", email);
  
  this.setEmail(email);
  this.setName(name);
  return "Success";
 }
}


Finally The User Object will be rendered to UI via EntryServlet.java
Wrap Up – Using the above Configuration we can set up google Guice Servlet Module in Web Application and take the advantages of easy to use, modularize and DI enabled code.

This post is written by
Soumitra Pathak - Linkedin, Facebook
He is a freelance writer, loves to explore latest features in Java technology.


How to Resolve Multiple Dependency in Google Guice API

How to Resolve Multiple Dependency in Google Guice API

As we have seen in previous post about how to Set up Dependency Injection using Google Guice API with Example. It is very easy to set up Dependency Injection using Google Guice as we don’t need any configuration xml unlike popular Spring Framework. As per the Concept we bind the Interface with Implementation in AbstractModule, but what if one interface has multiple implementation and we want Google Guice to resolve the Multiple Dependency and Inject the required Object at runtime.

In this post we will see how to overcome this problem. Let’s see the component one by one.


Configure Module to Enable the Dependency Injection :

To bind the interface with Implementation we need to create the Module. Guice provides two ways to resolve the Multiple Dependency -
1) Using Annotation.
2) Using Named Annotation (String)

1) Using Annotation

1. As shown below we need to create the SampleModule.Java and specify the binding for Interface to implementation through annotation.
public class SampleModule extends AbstractModule {

 // Bind interface with Implementation in Configure Method.  
 @Override
 protected void configure() {

  //Bind WebService to JMSServiceImpl with annotation JMS
  bind(WebService.class).annotatedWith(JMS.class).to(JMSServiceImpl.class);

  //Bind WebService to JMSServiceImpl with annotation REST
  bind(WebService.class).annotatedWith(REST.class).to(RESTServiceImpl.class);

  // Bind Clinet to RESTFul WebService with Annotation REST.
  bind(Client.class).annotatedWith(REST.class).to(RESTClient.class);

  // Bind Client to JMS Service with Annotation JMS.
  bind(Client.class).annotatedWith(JMS.class).to(JMSClient.class);
 } 
}


As you can see we have created Two Annotation JMS.java and REST.Java and bind the Interface with Implementation via Annotation for example Client Interface will be bind to RESTClient and RESTServiceImpl when marked with REST annotation.
Following is the definition for the Both JMS and REST Annotation –
import com.google.inject.BindingAnnotation;

@Retention(RetentionPolicy.RUNTIME)
@BindingAnnotation
@Target({ElementType.FIELD,ElementType.CONSTRUCTOR,ElementType.METHOD})
// Annotation can be Applied on Field, Constructor and Method
public @interface JMS{}


import com.google.inject.BindingAnnotation;

@Retention(RetentionPolicy.RUNTIME)
@BindingAnnotation
@Target({ElementType.FIELD,ElementType.CONSTRUCTOR,ElementType.METHOD})
// Annotation can be Applied on Field, Constructor and Method
public @interface REST{}


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).
public interface Client {
        String accessService();
}
@Singleton
public class RESTClient implements Client {

 @Inject
 @REST
 WebService restService;
 
 @Override
 public String accessService() {
  System.out.println("Access REST Client....");
  return restService.execute();
 }
}

As you can notice Guice will Inject restService as per binding defined using REST Annotation for interface WebService.

@Singleton
public class JMSClient implements Client {

 @Inject
 @JMS
 private WebService jmsService;
 
 @Override
 public String accessService() {
  System.out.println("Access JMS Client....");
  return jmsService.execute();
 }

}

As you can notice Guice will Inject restService as per binding defined using JMS Annotation for interface WebService.

3. Services and Implementation – As shown in SampleModule following are the Service and Corresponding Implementation –
public interface WebService {

 String execute();
} 


@Singleton
public class JMSServiceImpl implements WebService{

 @Override
 public String execute() {
  System.out.println("Executing JMS Service");
  return "Executing JMS Service";
 }
 
}


4. Main Application / Execute Program
As shown in the below code you can see how Guice is resolving the dependency by injecting the instance of jmsClient and restClient based on the Annotation specified @JMS and @REST
public class MainApplication {

 @Inject
 @JMS
 Client jmsClient;
 
 @Inject
 @REST
 Client restClient;
 
 public String processRequest(){
  System.out.println("Inside the Main Application...");
  return jmsClient.accessService()+"  "+restClient.accessService();  
  }
}





2) Using Named Annotation
Creating new Annotation types for every concrete implementation might not be useful as the sole purpose of having such an Annotation is just to mark the Implementation class instance needed by the Clients. Instead of Creating our own Annotation, we can use @Named annotation which can be use to provide the name to the binding.
There is one utility method Names.named() which returns @Named annotation. This can be use to mark the Implementation with @Named annotation.

bind(WebService.class).annotatedWith(Names.named("REST")).to(RESTServiceImpl.class);



1. Sample Module for the Named Annotation
public class SampleModule extends AbstractModule {

 // Bind interface with Implementation in Configure Method.  
 @Override
 protected void configure() {

  //Bind WebService to JMSServiceImpl with annotation JMS
  bind(WebService.class).annotatedWith(Names.named("JMS")).to(JMSServiceImpl.class);

  //Bind WebService to JMSServiceImpl with annotation REST
  bind(WebService.class).annotatedWith(Names.named("REST")).to(RESTServiceImpl.class);
  
  // Bind Clinet to RESTFul WebService with Annotation REST.
         bind(Client.class).annotatedWith(Names.named("REST")).to(RESTClient.class);

  // Bind Client to JMS Service with Annotation JMS.
         bind(Client.class).annotatedWith(Names.named("JMS")).to(JMSClient.class);
 } 
}


As you can see we have used Names.named() to mark the Implementation. This approach is easy to use and handy.

2. Interfaces and Implementation
Access the Define Mapping in SampleModule using @Named Annotation as shown below.
@Singleton
public class JMSClient implements Client {

 @Inject
 @Named("JMS")
 private WebService jmsService;
 
 @Override
 public String accessService() {
  System.out.println("Access JMS Client....");
  return jmsService.execute();
 }

}
public class RESTClient implements Client {

 @Inject
 @Named("REST")
 WebService restService;
 
 @Override
 public String accessService() {
  System.out.println("Access REST Client....");
  return restService.execute();
 }
 
}


3) Services and Implementation will be same as there is no dependency Involved.

4. Inject dependency in MainApplication using Named Annotation
As shown below injected the jmsClient and restClient. Rest of the code will be same.
public class MainApplication {

 @Inject
 @Named("JMS")
 Client jmsClient;
 
 @Inject
 @Named("REST")
 Client restClient;
 
 public String processRequest(){
  System.out.println("Inside the Main Application...");
  return jmsClient.accessService()+"  "+restClient.accessService();
 }
}





Entry Point of Application
public class TestMainApplication {
 
 public static void main(String[] args) {
  
  Injector injector = Guice.createInjector(new SampleModule());
  MainApplication mainApp = injector.getInstance(MainApplication.class);
  mainApp.processRequest();
 }
}


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.




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.
Following is the example to show case –
public class MainApplicationTest {

 private Injector injector;
 @Before
 public void setUp() throws Exception {
        injector = Guice.createInjector(new AbstractModule() {
             
            @Override
            protected void configure() {
             install(new SampleModule());
            }
        });
    }
 
    @After
    public void destroy() throws Exception {
        injector = null;
    }
 @Test
 public void testProcessRequest() {
  MainApplication mainApp = injector.getInstance(MainApplication.class);
  Assert.assertEquals("Executing JMS Service  Executing REST webService",mainApp.processRequest());
 }

}


Output  Following will be output after running the attached code.
START
Inside the Main Application...
Access JMS Client....
Executing JMS Service
Access REST Client....
Executing REST webService
END


This post is written by
Soumitra Pathak - Linkedin, Facebook
He is a freelance writer, loves to explore latest features in Java technology.


Set up Dependency Injection using Google Guice API with Example

Set up Dependency Injection using Google Guice API with Example

In this post we will see how to set up Google Guice for to enable Dependency Injection in project. Google Guice is an Agile Lightweight framework for Dependency Injection in Java Using Annotation. Guice works on interface implementation, i.e. it allows binding of the Interface to the implementation.

Guice promote to "Programming to Interface and not for implementation" i.e. we Create the Interface and Implementation and its Responsibility of Guice Framework to create objects and resolve dependency at the run time. Guice helps to keep code clean, Meaningful, easy to test and maintainable.

Using the below Example I will be explaining how to setup Google Guice to enable the Dependency Injection. In the below example we will try to Inject Client in MainApplication and then Inject Service into the Client.

You can download the required Goole Gruice API from Google-Guice-3.0.zip. You need to extract .zip file and add all .jar files in the build path / .classpath of the project.

Let’s see the component one by one.




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.

public class SampleModule extends AbstractModule {

 // Bind interface with Implementation in Configure Method.  
 @Override
 protected void configure() {
 // Bind Clinet to RESTFul WebService
 //bind(Client.class).to(RESTClient.class);
  
 // Bind Client to JMS Service.
 bind(Client.class).to(JMSClient.class);
  
 bind(JMSService.class).to(JMSServiceImpl.class);
 bind(RESTService.class).to(RESTServiceImpl.class);
 } 
}





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

package com.code.java.desk.api; 
public interface Client {
 
 String accessService();
}

@Singleton
public class JMSClient implements Client {

 // Instance Variable Injection.
        @Inject
 private JMSService jmsService;
 
 // Constructor Based Injection
 @Inject
 public JMSClient(JMSService jmsService) {
  super();
  this.jmsService = jmsService;
 }

 // Setter Method Injection.
 @Inject
 public void setJMSService(JMSService service){
  this.jmsService = service;
 }

 @Override
 public String accessService() {
  System.out.println("Access Client....");
  jmsService.execute();
  System.out.println("Exit Client Code...");
 }

}


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.

package com.code.java.desk.service;

public interface JMSService {

 void execute();
}

@Singleton
public class JMSServiceImpl implements JMSService{

 @Override
 public void execute() {
  System.out.println("Executing JMS Service");
 }
 
}


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

public class MainApplication {

 @Inject
 Client client;
 
 public String processRequest(){
  System.out.println("Inside the Main Application...");
  client.accessService();
  System.out.println("Exit Main Applicaion...");
 }
}


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

public class TestMainApplication {
 
 public static void main(String[] args) {
  
  Injector injector = Guice.createInjector(new SampleModule());
  MainApplication mainApp = injector.getInstance(MainApplication.class);
  mainApp.processRequest();
 }
}


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 –
public class MainApplicationTest {

    private Injector injector;
 @Before
 public void setUp() throws Exception {
          injector = Guice.createInjector(new AbstractModule() {
             
            @Override
            protected void configure() {
  install(new SampleModule());
                 bind(JMSService.class).to(JMSServiceImpl.class);
                 bind(Client.class).to(JMSClient.class);
            }
        });
    }
 
     @After
     public void destroy() throws Exception {
          injector = null;
    }
@Test
 public void testProcessRequest() {
  MainApplication mainApp = injector.getInstance(MainApplication.class);
  Assert.assertEquals("Executing JMS Service",mainApp.processRequest());
  }
}


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.