Injecting dependencies into microservices

duration 15 minutes
Git clone to get going right away:
git clone https://github.com/OpenLiberty/guide-cdi-intro.git
Copy Github clone command

Learn how to use Contexts and Dependency Injection (CDI) to manage scopes and inject dependencies into microservices.

What you’ll learn

You will learn how to use Contexts and Dependency Injection (CDI) to manage scopes and inject dependencies in a simple inventory management application.

The application that you will be working with is an inventory service, which stores the information about various JVMs that run on different systems. Whenever a request is made to the inventory service to retrieve the JVM system properties of a particular host, the inventory service communicates with the system service on that host to get these system properties. The system properties are then stored and returned.

You will use scopes to bind objects in this application to their well-defined contexts. CDI provides a variety of scopes for you to work with and while you will not use all of them in this guide, there is one for almost every scenario that you may encounter. Scopes are defined by using CDI annotations. You will also use dependency injection to inject one bean into another to make use of its functionalities. This enables you to inject the bean in its specified context without having to instantiate it yourself.

The implementation of the application and its services are provided for you in the start/src directory. The system service can be found in the start/src/main/java/io/openliberty/guides/system directory, and the inventory service can be found in the start/src/main/java/io/openliberty/guides/inventory directory. If you want to learn more about RESTful web services and how to build them, see Creating a RESTful web service for details about how to build the system service. The inventory service is built in a similar way.

What is CDI?

Contexts and Dependency Injection (CDI) defines a rich set of complementary services that improve the application structure. The most fundamental services that are provided by CDI are contexts that bind the lifecycle of stateful components to well-defined contexts, and dependency injection that is the ability to inject components into an application in a typesafe way. With CDI, the container does all the daunting work of instantiating dependencies, and controlling exactly when and how these components are instantiated and destroyed.

Getting started

The fastest way to work through this guide is to clone the Git repository and use the projects that are provided inside:

git clone https://github.com/openliberty/guide-cdi-intro.git
cd guide-cdi-intro

The start directory contains the starting project that you will build upon.

The finish directory contains the finished project that you will build.

Try what you’ll build

The finish directory in the root of this guide contains the finished inventory application. Give it a try before you proceed.

To try out the application, first navigate to the finish directory and then run the following Maven goals to build the application and run it inside Open Liberty:

cd finish
mvn install liberty:start-server

Point your browser to the http://localhost:9080/inventory/systems URL. This is the starting point of the inventory service and it displays the current contents of the inventory. As you might expect, these are empty since nothing is stored in the inventory yet. Next, point your browser to the http://localhost:9080/inventory/systems/localhost URL. You see a result in JSON format with the system properties of your local JVM. When you visit this URL, these system properties are automatically stored in the inventory. Go back to http://localhost:9080/inventory/systems and you see a new entry for localhost. For simplicity, only the OS name and username are shown here for each host. You can repeat this process for your own hostname or any other machine that is running the system service.

After you are done checking out the application, stop the Open Liberty server:

mvn liberty:stop-server

Handling dependencies in the application

You will use CDI to inject dependencies into the inventory manager application and learn how to manage the life cycles of your objects.

Managing scopes and contexts

Navigate to the start directory to begin.

Create the InventoryManager class.
src/main/java/io/openliberty/guides/inventory/InventoryManager.java

InventoryManager.java

 1package io.openliberty.guides.inventory;
 2
 3import java.util.ArrayList;
 4import java.util.Collections;
 5import java.util.List;
 6import java.util.Properties;
 7import io.openliberty.guides.inventory.client.SystemClient;
 8import io.openliberty.guides.inventory.model.InventoryList;
 9import io.openliberty.guides.inventory.model.SystemData;
10import javax.enterprise.context.ApplicationScoped;
11import javax.inject.Inject;
12
13@ApplicationScoped
14public class InventoryManager {
15
16  private List<SystemData> systems = Collections.synchronizedList(new ArrayList<>());
17
18  public void add(String hostname, Properties systemProps) {
19    Properties props = new Properties();
20    props.setProperty("os.name", systemProps.getProperty("os.name"));
21    props.setProperty("user.name", systemProps.getProperty("user.name"));
22
23    SystemData system = new SystemData(hostname, props);
24    if (!systems.contains(system)) {
25      systems.add(system);
26    }
27  }
28
29  public InventoryList list() {
30    return new InventoryList(systems);
31  }
32}

This bean contains two simple functions. The add() function is for adding entries to the inventory. The list() function is for listing all the entries currently stored in the inventory.

This bean must be persistent between all of the clients, which means multiple clients need to share the same instance. To achieve this by using CDI, you can simply add the @ApplicationScoped annotation onto the class.

This annotation indicates that this particular bean is to be initialized once per application. By making it application-scoped, the container ensures that the same instance of the bean is used whenever it is injected into the application.

Create the InventoryResource class.
src/main/java/io/openliberty/guides/inventory/InventoryResource.java

InventoryResource.java

 1package io.openliberty.guides.inventory;
 2
 3import java.util.Properties;
 4import javax.enterprise.context.RequestScoped;
 5import javax.inject.Inject;
 6import javax.ws.rs.GET;
 7import javax.ws.rs.Path;
 8import javax.ws.rs.PathParam;
 9import javax.ws.rs.Produces;
10import javax.ws.rs.core.MediaType;
11import javax.ws.rs.core.Response;
12import io.openliberty.guides.inventory.model.InventoryList;
13import io.openliberty.guides.inventory.client.SystemClient;
14
15@RequestScoped
16@Path("/systems")
17public class InventoryResource {
18
19  @Inject
20  InventoryManager manager;
21
22  @Inject
23  SystemClient systemClient;
24
25  @GET
26  @Path("/{hostname}")
27  @Produces(MediaType.APPLICATION_JSON)
28  public Response getPropertiesForHost(@PathParam("hostname") String hostname) {
29    // Get properties for host
30    Properties props = systemClient.getProperties(hostname);
31    if (props == null) {
32      return Response.status(Response.Status.NOT_FOUND)
33                     .entity("ERROR: Unknown hostname or the system service may not be "
34                             + "running on " + hostname)
35                     .build();
36    }
37
38    // Add to inventory
39    manager.add(hostname, props);
40    return Response.ok(props).build();
41  }
42
43  @GET
44  @Produces(MediaType.APPLICATION_JSON)
45  public InventoryList listContents() {
46    return manager.list();
47  }
48}

The inventory resource is a RESTful service that is served at the inventory/systems endpoint.

Add the @RequestScoped annotation on the class to indicate that this bean is to be initialized once for every request. In other words, the bean is instantiated when the request is received and destroyed when a response is sent back to the client. While this bean can also be application-scoped, request scope is short-lived and is therefore ideal for HTTP requests.

Injecting a dependency

Refer to the InventoryResource class you created above.

The @Inject annotation indicates a dependency injection. You are injecting your InventoryManager and SystemClient beans into the InventoryResource class. This injects the beans in their specified context and makes all of their functionalities available without the need of instantiating them yourself. The injected bean InventoryManager can then be invoked directly through the manager.add(hostname, props) and manager.list() function calls. The injected bean SystemClient can be invoked through the systemClient.getProperties(hostname) function call.

Finally, you have a client component SystemClient that can be found in the src/main/java/io/openliberty/guides/inventory/client directory. This class communicates with the system service to retrieve the JVM system properties for a particular host that exposes them. This class also contains detailed Javadocs that you can read for reference.

Your inventory application is now completed.

InventoryResource.java

 1package io.openliberty.guides.inventory;
 2
 3import java.util.Properties;
 4import javax.enterprise.context.RequestScoped;
 5import javax.inject.Inject;
 6import javax.ws.rs.GET;
 7import javax.ws.rs.Path;
 8import javax.ws.rs.PathParam;
 9import javax.ws.rs.Produces;
10import javax.ws.rs.core.MediaType;
11import javax.ws.rs.core.Response;
12import io.openliberty.guides.inventory.model.InventoryList;
13import io.openliberty.guides.inventory.client.SystemClient;
14
15@RequestScoped
16@Path("/systems")
17public class InventoryResource {
18
19  @Inject
20  InventoryManager manager;
21
22  @Inject
23  SystemClient systemClient;
24
25  @GET
26  @Path("/{hostname}")
27  @Produces(MediaType.APPLICATION_JSON)
28  public Response getPropertiesForHost(@PathParam("hostname") String hostname) {
29    // Get properties for host
30    Properties props = systemClient.getProperties(hostname);
31    if (props == null) {
32      return Response.status(Response.Status.NOT_FOUND)
33                     .entity("ERROR: Unknown hostname or the system service may not be "
34                             + "running on " + hostname)
35                     .build();
36    }
37
38    // Add to inventory
39    manager.add(hostname, props);
40    return Response.ok(props).build();
41  }
42
43  @GET
44  @Produces(MediaType.APPLICATION_JSON)
45  public InventoryList listContents() {
46    return manager.list();
47  }
48}

SystemClient.java

 1package io.openliberty.guides.inventory.client;
 2
 3import javax.enterprise.context.RequestScoped;
 4import javax.ws.rs.client.Client;
 5import javax.ws.rs.client.ClientBuilder;
 6import javax.ws.rs.client.Invocation.Builder;
 7import javax.ws.rs.core.HttpHeaders;
 8import javax.ws.rs.core.MediaType;
 9import javax.ws.rs.core.Response;
10import javax.ws.rs.core.Response.Status;
11import java.util.Properties;
12import java.net.URI;
13
14@RequestScoped
15public class SystemClient {
16
17  // Constants for building URI to the system service.
18  private final int DEFAULT_PORT = Integer.valueOf(System.getProperty("default.http.port"));
19  private final String SYSTEM_PROPERTIES = "/system/properties";
20  private final String PROTOCOL = "http";
21
22  // Wrapper function that gets properties
23  public Properties getProperties(String hostname) {
24    String url = buildUrl(PROTOCOL, hostname, DEFAULT_PORT, SYSTEM_PROPERTIES);
25    Builder clientBuilder = buildClientBuilder(url);
26    return getPropertiesHelper(clientBuilder);
27  }
28
29  /**
30   * Builds the URI string to the system service for a particular host.
31   * @param protocol
32   *          - http or https.
33   * @param host
34   *          - name of host.
35   * @param port
36   *          - port number.
37   * @param path
38   *          - Note that the path needs to start with a slash!!!
39   * @return String representation of the URI to the system properties service.
40   */
41  protected String buildUrl(String protocol, String host, int port, String path) {
42    try {
43      URI uri = new URI(protocol, null, host, port, path, null, null);
44      return uri.toString();
45    } catch (Exception e) {
46      System.err.println("Exception thrown while building the URL: " + e.getMessage());
47      return null;
48    }
49  }
50
51  // Method that creates the client builder
52  protected Builder buildClientBuilder(String urlString) {
53    try {
54      Client client = ClientBuilder.newClient();
55      Builder builder = client.target(urlString).request();
56      return builder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
57    } catch (Exception e) {
58      System.err.println("Exception thrown while building the client: " + e.getMessage());
59      return null;
60    }
61  }
62
63  // Helper method that processes the request
64  protected Properties getPropertiesHelper(Builder builder) {
65    try {
66      Response response = builder.get();
67      if (response.getStatus() == Status.OK.getStatusCode()) {
68        return response.readEntity(Properties.class);
69      } else {
70        System.err.println("Response Status is not OK.");
71      }
72    } catch (RuntimeException e) {
73      System.err.println("Runtime exception: " + e.getMessage());
74    } catch (Exception e) {
75      System.err.println("Exception thrown while invoking the request: " + e.getMessage());
76    }
77    return null;
78  }
79
80}

Building and running the application

To build the application, run the Maven install phase from the command line in the start directory:

mvn install

This command builds the application and creates a .war file in the target directory. It also configures and installs Open Liberty into the target/liberty/wlp directory.

Next, run the Maven liberty:start-server goal:

mvn liberty:start-server

This goal starts an Open Liberty server instance. Your Maven pom.xml is already configured to start the application in this server instance.

You can find the inventory and system services at the following URLs:

If you make changes to the code, use the Maven compile goal to rebuild the application and have the running Open Liberty server pick them up automatically:

mvn compile

To stop the Open Liberty server, run the Maven liberty:stop-server goal:

mvn liberty:stop-server

Testing the inventory application

While you can test your application manually, you should rely on automated tests since they trigger a failure whenever a code change introduces a defect. Since the application is a RESTful web service application, you can use JUnit and the RESTful web service Client API to write tests. In testing the functionality of the application, the scopes and dependencies are being tested.

Create the InventoryEndpointTest class.
src/test/java/it/io/openliberty/guides/inventory/InventoryEndpointTest.java

The @BeforeClass annotation is placed on a method that runs before any of the test cases. In this case, the oneTimeSetup() method retrieves the port number for the Open Liberty server and builds a base URL string that is used throughout the tests.

The @Before and @After annotations are placed on methods that run before and after every test case. These methods are generally used to perform any setup and teardown tasks. In this case, the setup() method creates a JAX-RS client, which makes HTTP requests to the inventory service. This client must also be registered with a JSON-P provider (JsrJsonpProvider) to process JSON resources. The teardown() method simply destroys this client instance.

See the following descriptions of the test cases:

  • testEmptyInventory() verifies that the inventory is initially empty when the server first starts up.

  • testHostRegistration() verifies that a host is correctly added to the inventory.

  • testSystemPropertiesMatch() verifies that the JVM system properties returned by the system service match the ones stored in the inventory service.

  • testUnknownHost() verifies that an unknown host or a host that does not expose their JVM system properties is correctly handled as an error.

To force these test cases to run in a particular order, put them in a testSuite() method and label it with a @Test annotation so that it automatically runs when your test class run.

Finally, the src/test/java/it/io/openliberty/guides/system/SystemEndpointTest.java file is included for you to test the basic functionality of the system service. If a test failure occurs, then you might have introduced a bug into the code.

InventoryEndpointTest.java

  1package it.io.openliberty.guides.inventory;
  2
  3import static org.junit.Assert.assertEquals;
  4import static org.junit.Assert.assertTrue;
  5
  6import javax.json.JsonObject;
  7import javax.ws.rs.client.Client;
  8import javax.ws.rs.client.ClientBuilder;
  9import javax.ws.rs.core.MediaType;
 10import javax.ws.rs.core.Response;
 11
 12import org.apache.cxf.jaxrs.provider.jsrjsonp.JsrJsonpProvider;
 13import org.junit.After;
 14import org.junit.Before;
 15import org.junit.BeforeClass;
 16import org.junit.Test;
 17
 18public class InventoryEndpointTest {
 19
 20  private static String port;
 21  private static String baseUrl;
 22
 23  private Client client;
 24
 25  private final String SYSTEM_PROPERTIES = "system/properties";
 26  private final String INVENTORY_SYSTEMS = "inventory/systems";
 27
 28  @BeforeClass
 29  public static void oneTimeSetup() {
 30    port = System.getProperty("liberty.test.port");
 31    baseUrl = "http://localhost:" + port + "/";
 32  }
 33
 34  @Before
 35  public void setup() {
 36    client = ClientBuilder.newClient();
 37    client.register(JsrJsonpProvider.class);
 38  }
 39
 40  @After
 41  public void teardown() {
 42    client.close();
 43  }
 44
 45  @Test
 46  public void testSuite() {
 47    this.testEmptyInventory();
 48    this.testHostRegistration();
 49    this.testSystemPropertiesMatch();
 50    this.testUnknownHost();
 51  }
 52
 53  public void testEmptyInventory() {
 54    Response response = this.getResponse(baseUrl + INVENTORY_SYSTEMS);
 55    this.assertResponse(baseUrl, response);
 56
 57    JsonObject obj = response.readEntity(JsonObject.class);
 58
 59    int expected = 0;
 60    int actual = obj.getInt("total");
 61    assertEquals("The inventory should be empty on application start but it wasn't",
 62                 expected, actual);
 63
 64    response.close();
 65  }
 66
 67  public void testHostRegistration() {
 68    this.visitLocalhost();
 69
 70    Response response = this.getResponse(baseUrl + INVENTORY_SYSTEMS);
 71    this.assertResponse(baseUrl, response);
 72
 73    JsonObject obj = response.readEntity(JsonObject.class);
 74
 75    int expected = 1;
 76    int actual = obj.getInt("total");
 77    assertEquals("The inventory should have one entry for localhost", expected,
 78                 actual);
 79
 80    boolean localhostExists = obj.getJsonArray("systems").getJsonObject(0)
 81                                 .get("hostname").toString()
 82                                 .contains("localhost");
 83    assertTrue("A host was registered, but it was not localhost",
 84               localhostExists);
 85
 86    response.close();
 87  }
 88
 89  public void testSystemPropertiesMatch() {
 90    Response invResponse = this.getResponse(baseUrl + INVENTORY_SYSTEMS);
 91    Response sysResponse = this.getResponse(baseUrl + SYSTEM_PROPERTIES);
 92
 93    this.assertResponse(baseUrl, invResponse);
 94    this.assertResponse(baseUrl, sysResponse);
 95
 96    JsonObject jsonFromInventory = (JsonObject) invResponse.readEntity(JsonObject.class)
 97                                                           .getJsonArray("systems")
 98                                                           .getJsonObject(0)
 99                                                           .get("properties");
100
101    JsonObject jsonFromSystem = sysResponse.readEntity(JsonObject.class);
102
103    String osNameFromInventory = jsonFromInventory.getString("os.name");
104    String osNameFromSystem = jsonFromSystem.getString("os.name");
105    this.assertProperty("os.name", "localhost", osNameFromSystem,
106                        osNameFromInventory);
107
108    String userNameFromInventory = jsonFromInventory.getString("user.name");
109    String userNameFromSystem = jsonFromSystem.getString("user.name");
110    this.assertProperty("user.name", "localhost", userNameFromSystem,
111                        userNameFromInventory);
112
113    invResponse.close();
114    sysResponse.close();
115  }
116
117  public void testUnknownHost() {
118    Response response = this.getResponse(baseUrl + INVENTORY_SYSTEMS);
119    this.assertResponse(baseUrl, response);
120
121    Response badResponse = client.target(baseUrl + INVENTORY_SYSTEMS + "/"
122        + "badhostname").request(MediaType.APPLICATION_JSON).get();
123
124    String obj = badResponse.readEntity(String.class);
125
126    boolean isError = obj.contains("ERROR");
127    assertTrue("badhostname is not a valid host but it didn't raise an error",
128               isError);
129
130    response.close();
131    badResponse.close();
132  }
133
134  private Response getResponse(String url) {
135    return client.target(url).request().get();
136  }
137
138  private void assertResponse(String url, Response response) {
139    assertEquals("Incorrect response code from " + url, 200,
140                 response.getStatus());
141  }
142
143  private void assertProperty(String propertyName, String hostname,
144      String expected, String actual) {
145    assertEquals("JVM system property [" + propertyName + "] "
146        + "in the system service does not match the one stored in "
147        + "the inventory service for " + hostname, expected, actual);
148  }
149
150  private void visitLocalhost() {
151    Response response = this.getResponse(baseUrl + SYSTEM_PROPERTIES);
152    this.assertResponse(baseUrl, response);
153    response.close();
154
155    Response targetResponse = client.target(baseUrl + INVENTORY_SYSTEMS
156        + "/localhost").request().get();
157    targetResponse.close();
158  }
159}

SystemEndpointTest.java

 1package it.io.openliberty.guides.system;
 2
 3import static org.junit.Assert.assertEquals;
 4import javax.json.JsonObject;
 5import javax.ws.rs.client.Client;
 6import javax.ws.rs.client.ClientBuilder;
 7import javax.ws.rs.client.WebTarget;
 8import javax.ws.rs.core.Response;
 9
10import org.apache.cxf.jaxrs.provider.jsrjsonp.JsrJsonpProvider;
11import org.junit.Test;
12
13public class SystemEndpointTest {
14
15 @Test
16 public void testGetProperties() {
17     String port = System.getProperty("liberty.test.port");
18     String url = "http://localhost:" + port + "/";
19
20     Client client = ClientBuilder.newClient();
21     client.register(JsrJsonpProvider.class);
22
23     WebTarget target = client.target(url + "system/properties");
24     Response response = target.request().get();
25
26     assertEquals("Incorrect response code from " + url, 200, response.getStatus());
27
28     JsonObject obj = response.readEntity(JsonObject.class);
29
30     assertEquals("The system property for the local and remote JVM should match",
31                  System.getProperty("os.name"),
32                  obj.getString("os.name"));
33
34     response.close();
35 }
36}

Running the tests

If the server is still running from the previous steps, stop it using the Maven liberty:stop-server goal from command line in the start directory:

mvn liberty:stop-server

Then, verify that the tests pass using the Maven verify goal:

mvn verify

It may take some time before build is complete. If the tests pass, you will see a similar output to the following:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running it.io.openliberty.guides.system.SystemEndpointTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.99 sec - in it.io.openliberty.guides.system.SystemEndpointTest
Running it.io.openliberty.guides.inventory.InventoryEndpointTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.325 sec - in it.io.openliberty.guides.inventory.InventoryEndpointTest

Results :

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

To see whether the tests detect a failure, change the endpoint for the inventory service in the src/main/java/io/openliberty/guides/inventory/InventoryResource.java file to something else, then run the Maven build again. You see a test failure occur.

InventoryResource.java

 1package io.openliberty.guides.inventory;
 2
 3import java.util.Properties;
 4import javax.enterprise.context.RequestScoped;
 5import javax.inject.Inject;
 6import javax.ws.rs.GET;
 7import javax.ws.rs.Path;
 8import javax.ws.rs.PathParam;
 9import javax.ws.rs.Produces;
10import javax.ws.rs.core.MediaType;
11import javax.ws.rs.core.Response;
12import io.openliberty.guides.inventory.model.InventoryList;
13import io.openliberty.guides.inventory.client.SystemClient;
14
15@RequestScoped
16@Path("/systems")
17public class InventoryResource {
18
19  @Inject
20  InventoryManager manager;
21
22  @Inject
23  SystemClient systemClient;
24
25  @GET
26  @Path("/{hostname}")
27  @Produces(MediaType.APPLICATION_JSON)
28  public Response getPropertiesForHost(@PathParam("hostname") String hostname) {
29    // Get properties for host
30    Properties props = systemClient.getProperties(hostname);
31    if (props == null) {
32      return Response.status(Response.Status.NOT_FOUND)
33                     .entity("ERROR: Unknown hostname or the system service may not be "
34                             + "running on " + hostname)
35                     .build();
36    }
37
38    // Add to inventory
39    manager.add(hostname, props);
40    return Response.ok(props).build();
41  }
42
43  @GET
44  @Produces(MediaType.APPLICATION_JSON)
45  public InventoryList listContents() {
46    return manager.list();
47  }
48}

Great work! You’re done!

You have just completed building a simple inventory application using CDI services in Open Liberty.

Guide Attribution

Injecting dependencies into microservices by Open Liberty is licensed under CC BY-ND 4.0

Copied to clipboard
Copy code block
Copy file contents
Git clone this repo to get going right away:
git clone https://github.com/OpenLiberty/guide-cdi-intro.git
Copy github clone command
Copied to clipboard

Nice work! Where to next?

What could make this guide better?

Raise an issue to share feedback

Create a pull request to contribute to this guide

Need help?

Ask a question on Stack Overflow

What did you think of this guide?

Extreme Dislike Dislike Like Extreme Like