Dependency Injection
Java Platform, Enterprise Edition (Java EE) 8
The Java EE Tutorial

Previous Next Contents

Dependency Injection

Dependency injection enables you to turn regular Java classes into managed objects and to inject them into any other managed object. Using dependency injection, your code can declare dependencies on any managed object. The container automatically provides instances of these dependencies at the injection points at runtime, and it also manages the lifecycle of these instances for you.

Dependency injection in Java EE defines scopes, which determine the lifecycle of the objects that the container instantiates and injects. For example, a managed object that is only needed to respond to a single client request (such as a currency converter) has a different scope than a managed object that is needed to process multiple client requests within a session (such as a shopping cart).

You can define managed objects (also called managed beans) that you can later inject by assigning a scope to a regular class:

@javax.enterprise.context.RequestScoped
public class CurrencyConverter { ... }

Use the javax.inject.Inject annotation to inject managed beans; for example:

public class MyServlet extends HttpServlet {
    @Inject CurrencyConverter cc;
    ...
}

As opposed to resource injection, dependency injection is typesafe because it resolves by type. To decouple your code from the implementation of the managed bean, you can reference the injected instances using an interface type and have your managed bean implement that interface.

For more information about dependency injection, see Chapter 25, "Introduction to Contexts and Dependency Injection for Java EE" and JSR 299 (Contexts and Dependency Injection for the Java EE Platform).


Previous Next Contents
Oracle Logo  Copyright © 2017, Oracle and/or its affiliates. All rights reserved.