DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Understanding Jakarta EE 8 - CDI Part 1
  • Dependency Injection in Spring
  • Smart Dependency Injection With Spring: Assignability (Part 2 of 3)
  • Understanding Jakarta EE 8 CDI (Part 2): Qualifying Your Beans

Trending

  • Four Essential Tips for Building a Robust REST API in Java
  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • Ensuring Configuration Consistency Across Global Data Centers
  • Next-Gen IoT Performance Depends on Advanced Power Management ICs
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. JavaEE Contexts and Dependency Injection (CDI) First Steps

JavaEE Contexts and Dependency Injection (CDI) First Steps

How to use Java EE and CDI to execute dependency injections.

By 
Hany Ahmed user avatar
Hany Ahmed
·
Dec. 21, 15 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
22.0K Views

Join the DZone community and get the full member experience.

Join For Free

Dependency Injections are defined as the ability to inject components into an application in a typesafe way, including the ability to choose at deployment time which implementation of a particular interface to inject.

Loose Coupling

In a regular OO Composition you are including an object into another, the composed object should be instantiated by hand.

The objective here is to decouple these two objects, so the composed object type shouldn’t be a concrete class, It should be an abstract class or an interface, We’re aiming also not to instantiate a new object and assign it to this reference. Someone else (the application server) would search at runtime for a convenient implementation for that reference of type interface then instantiate a new object from it then assign (inject) it to the composing object.

Almost every bean could be injected in CDI plus some other resources that can be injected like EJB Session beans, Persistence contexts and Data sources.

Enabling CDI

To enable CDI in a java web project the WEB-INF directory should contain a file called beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>

First Steps in CDI

Suppose we have this interface:

public interface Printer {
    void print(String text);
}

We’ll provide an implementation for this interface:

public class SimplePrinter implements Printer{

    @Override
    public void print(String text) {
        System.out.println(text);
    }

}

In any class we can make a refrence from Printer and tell the container to look up for an implementation and inject it:

@WebServlet(name = "demo", urlPatterns = "/demo")
public class DemoServlet extends HttpServlet {

    @Inject Printer printer;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        printer.print("Helloooooo");

    }    

}

Multiple Candidates for Injection

If we tries to inject a type using interface, and there are many implementations for this interface

public class FancyPrinter implements Printer{

    @Override
    public void print(String text) {
        System.out.println(" #### " + text + " #### ");
    }

}

The container will not succeed to inject the appropriate one, causing an error like this:

CDI deployment failure:WELD-001408 Unsatisfied dependencies for type [Printer] with qualifiers [@Default] at injection point [[BackedAnnotatedField] @Inject demo.DemoServlet.anonymousPrinter]

The solution for this problem is to define the class you want to inject by providing an additional information that would help the container to select the best match. We can simply make a new qualifier annotation to help the container do so.

Our new annotation should be annotated with three anotations:

  • @Qualifier To define that this annotation would be a qualifier.
  • @Retention(RetentionPolicy.RUNTIME) To define that this annotation would be available at runtime.
  • @Target({ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) Qualifier annotation should be applicable to annotate these types: type(class/interface), class filed, method parameter, and method.
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
public @interface Simple {

}

The next step is to annotate our implementation with this new annotation:

@Simple
public class SimplePrinter implements Printer{

    @Override
    public void print(String text) {
        System.out.println(text);
    }

}

And inject it using the same annotation:

// = Inject the bean that implements Printer and has an annotation @simple
@Inject @Simple Printer printer;

Another solution is to use the same qualifier annotation but with different values for multiple implemenations.

We can make a new annotation that takes a value like this one:

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE})
public @interface Labeled {
    String value();
}

Then rewrite our implementations to use this new annotation:

@Labeled("simple")
public class SimplePrinter implements Printer{

    @Override
    public void print(String text) {
        System.out.println(text);
    }

}
@Labeled("fancy")
public class FancyPrinter implements Printer{

    @Override
    public void print(String text) {
        System.out.println(" #### " + text + " #### ");
    }

}

Then we can inject both by this way:

//Inject the bean that implements Printer and has an annotation @Labeled that has a value “simple”
@Inject @Labeled("simple") Printer simplePrinter;

//Inject the bean that implements Printer and has an annotation @Labeled that has a value “fancy”
@Inject @Labeled("fancy") Printer fancePrinter;

Produces Method

Sometimes you want to inject a class that you can’t modify its source (that’s imported from an external library or in the java classes).

Other times you want to inject a bean that needs to have some initialization.

The solution for both cases is to make a method that’s responsible for generating the bean:

public class Utils {

    @Produces @LoggedIn
    public User getLoggedInUser() {
        User user = new User();
        user.setId(11);
        user.setName("Ahmed");
        return user;
    }

    @Produces
    public Random getRandom() {
        return new Random(System.currentTimeMillis());
    }

}

Now you can inject both simply by these lines:

@Inject @LoggedIn User user;
@Inject Random random;

Bean Scopes

The default behavior for injection is called Dependent, means that in every injection point a new instance of the bean would be created and injected.

There’re many scopes for the injection, we can annotate our implementations with these scope annotations to control bean injection

  • @Dependent in every injection point a new instance would be created.

  • @RequestScoped The same bean would be injected as we still in the scope of the same request.

  • @SessionScoped The same bean would be injected for every session, thus means that a bean for every user would be created and injected.

  • @ApplicationScoped Only one bean would be created and injected for all users for all injection points (=Singleton).

  • @ConversationScoped A custom scope that its lifetime is bigger than @RequestScoped and less than @SessionScopedIt’s used in wizard pages to reach the same bean instance across multiple pages.

CDI Dependency injection Bean (software) Spring Framework Annotation Implementation

Published at DZone with permission of Hany Ahmed. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Understanding Jakarta EE 8 - CDI Part 1
  • Dependency Injection in Spring
  • Smart Dependency Injection With Spring: Assignability (Part 2 of 3)
  • Understanding Jakarta EE 8 CDI (Part 2): Qualifying Your Beans

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: