Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

CDI (Part 4): Lazy Initialization

DZone's Guide to

CDI (Part 4): Lazy Initialization

Let's move onto another big benefit of CDI: lazy initialization. See how and when to implement it in your Java projects with this in-depth tutorial.

· Java Zone ·
Free Resource

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Hello!

This is the Part 4 of the CDI Series in Java that contains:

  • Part 1: Factory in CDI with @Produces annotation
  • Part 2: CDI Qualifiers
  • Part 3: Events and Observers in CDI
  • Part 4: CDI and Lazy Initialization
  • Part 5: Interceptors in CDI
  • Part 6: CDI Dependency Injection and Alternatives
  • Part 7: Working with CDI Decorators

In the today's post, we're going to see lazy initialization using CDI!

Let's contextualize our application problem.

  • We must have a Checkout class
  • We must send an email when a checkout is finished
  • We must create a metric when a checkout is finished

But wait! We can just send an email if the user is not optIn, right? We wouldn't want to spam him!

Step 1: Creating the Entire Scenario

The first class will use CDI 2.0 in standalone mode just to keep things simple. With CDI 2.0, we can use CDI in a standalone environment, but you can use lazy initialization from CDI 1.0.

The following class creates the CDI container that allows us to use Dependency Injection:

public class MainApplication {

    public static void main(String[] args) {
        try (CDI<Object> container = new Weld().initialize()) {
            Checkout checkout = container.select(Checkout.class).get();

            User user = new User("welcome@hackingcode.com", true);

            checkout.finishCheckout(user);
        }
    }

}


Ok. We don't have the User class, so let's create it:

public class User {

    private String email;
    private boolean optIn;

    public User(String email, boolean optIn) {
        this.email = email;
        this.optIn = optIn;
    }

    public String getEmail() {
        return this.email;
    }

    public boolean isOptIn() {
        return this.optIn;
    }

}


It's time to create the Checkout class:

public class Checkout {

    @Inject
    private EmailSender emailSender;

    @Inject
    private MetricCreator metricCreator;

    public void finishCheckout(User user) {
        System.out.println("Finishing Checkout");

        emailSender.sendEmailFor(user);

        metricCreator.createMetric();
    }

}


Last, let's create the EmailSender and MetricCreator classes:

public class EmailSender {

    public EmailSender() {
        System.out.println("Constructing the EmailSender");
    }

    public void sendEmailFor(User user) {
        System.out.println("Sending email to: " + user.getEmail());
    }

}


public class MetricCreator {

    public MetricCreator() {
        System.out.println("Constructing the MetricCreator");
    }

    public void createMetric() {
        System.out.println("Creating new Metric for the new Checkout");
    }

}


Awesome! Pretty simple so far. Let's run the main() method:

Constructing the EmailSender
Constructing the MetricCreator
Finishing Checkout
Sending email to: welcome@hackingcode.com
Creating new Metric for the new Checkout


As you can see, everything is up and running as we expected, right?

Wait! We forgot to test if the user is an OptIn user, otherwise, we'll send emails that can go directly to the spam box

Fixing it:

public class Checkout {

    public void finishCheckout(User user) {
        System.out.println("Finishing Checkout");

        if (user.isOptIn()) { //yes, just Optin users!
            emailSender.sendEmailFor(user);
        }

        metricCreator.createMetric();
    }

}


Cool! Let's run it again:

Constructing the EmailSender
Constructing the MetricCreator
Finishing Checkout
Sending email to: welcome@hackingcode.com
Creating new Metric for the new Checkout


Nothing new here.

But if we change that?

public class MainApplication {

    public static void main(String[] args) {
        try (CDI<Object> container = new Weld().initialize()) {
            Checkout checkout = container.select(Checkout.class).get();

            User user = new User("welcome@hackingcode.com", false); // Now the user is not OptIn :(

            checkout.finishCheckout(user);
        }
    }

}


As you can see, the User is no longer an OptIn.

That's ok, let's run the main() method again:

Constructing the EmailSender
Constructing the MetricCreator
Finishing Checkout
Creating new Metric for the new Checkout


As you can see in the message that has been printed, we are not sending email to the User anymore.

But wait! Did you read all of the log? In particular:

Constructing the EmailSender


Bt the user is not an OpInt, and I will not send an email to them! So I probably don't need to construct the EmailSender, right?

Yes, CDI will inject your dependencies, even if you do not use them!

When CDI needs to inject the Checkout class, CDI will say:

  • Hmm, I need to create an instance of the Checkout class for you.
  • But the Checkout class has a dependency on the EmailSender class. I'll inject it, and I don't care if you use it or not.
  • But the Checkout class has a dependency on the MetricCreator class. Again, I'll inject it for you, and I don't care if you use it.

And that's it! But sometimes the class being injected is:

  • Heavy
  • Has other dependencies (that will be injected by CDI) that could be really expensive
  • Or we just don't know if it will be used

Step 2: CDI Lazy Injection

CDI has an important interface called Instance. This interface allows the application to dynamically obtain instances that may or may not have qualifiers.

To use this interface, you can ask yourself a few questions:

  • Can the bean type vary dynamically at runtime?
  • Does the bean type need to be injected based on qualifiers at runtime?
  • Do you need to iterate through all beans to pick up which you are interested in?

If you answer these quiestions affirmatively, you may use the Instance interface to Inject the bean dynamically

So, that's our case! Let's use the Instance interface to inject the EmailSender object only if the user is OptIn:

public class Checkout {

    @Inject
    private Instance<EmailSender> emailSender;

    @Inject
    private MetricCreator metricCreator;

    public void finishCheckout(User user) {
        System.out.println("Finishing Checkout");

        if (user.isOptIn()) { //yes, just Optin users!
            emailSender.get().sendEmailFor(user);
        }

        metricCreator.createMetric();
    }

}


In the code above, notice that we can't just call emailSender.sendEmailFor(user) since the type of the Injected point is Instance and not EmailSender.

To retrieve the instance and take the object injected, we must use the . get() method from the Instance interface.

If we run our code again, we will have the following result:

Constructing the MetricCreator
Finishing Checkout
Creating new Metric for the new Checkout


Great! Our user is not OptIn and the EmailSender class was not created. It will be created just if the user is OptIn!

Step 3: Lazy Initialization in a Bad Code Design

Imagine the following code:

public class Checkout {

    @Inject
    private Payment payment;

    @Inject
    private Stock stock;

    @Inject
    private Shipping shipping;

    public void finishFirstLogic(Order order) {
        payment.start();
    }

    public void finishSecondLogic(Order order) {
        if (shipping.allowedFor(order)) {
            stock.remove(order.getItem());
        }
    }

    public void finishThirdLogic(Order order) {
        if (shipping.allowedFor(order)) {
            payment.start();
        }
    }

    public void finishFourthLogic(Order order) {
        if (payment.allowedFor(order.getUser())) {
            payment.start();
        }
    }

}


Besides the terrible example, this code can have bad code design. Notice that the Stock object is used by just 1 method out of 4.

Again, even if you're calling the finishThirdLogic() method, the Stock object will be injected by CDI.

In this situation, you could use lazy initialization to inject the Stock object only in the desired method:

public class Checkout {

    @Inject
    private Payment payment;

    @Inject
    private Instance<Stock> stock;

    @Inject
    private Shipping shipping;

    public void finishFirstLogic(Order order) {
        payment.start();
    }

    public void finishSecondLogic(Order order) {
        if (shipping.allowedFor(order)) {
            stock.get().remove(order.getItem()); //Lazy Initialized :)
        }
    }

    public void finishThirdLogic(Order order) {
        if (shipping.allowedFor(order)) {
            payment.start();
        }
    }

    public void finishFourthLogic(Order order) {
        if (payment.allowedFor(order.getUser())) {
            payment.start();
        }
    }

}


That's it! Lazy initialization with CDI.

Would you like to get the complete code? Get it from this GitHub repository! You can try yourself!

I hope that this post was helpful to you! Have any questions, suggestions, or errors you want to discuss? Please feel free to write a comment!

It's time to jump into the next part: Part 5: Interceptors in CDI

Thanks!

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Topics:
cdi ,cdi 2.0 ,lazy initialization ,java ,dependency injection ,inversion of control ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}