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
Please enter at least three characters to search
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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

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

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

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

Related

  • Introducing SmallRye LLM: Injecting Langchain4J AI Services
  • Injecting Implementations With Jakarta CDI Using Polymorphism
  • Extending the Power of Jakarta EE and MicroProfile With CDI Extension
  • Archiving Composition Over the Heritage With CDI Decorator and Delegator

Trending

  • Monoliths, REST, and Spring Boot Sidecars: A Real Modernization Playbook
  • Securing the Future: Best Practices for Privacy and Data Governance in LLMOps
  • Is Big Data Dying?
  • Using Python Libraries in Java
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. CDI (Part 4): Lazy Initialization

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.

By 
Alexandre Gama user avatar
Alexandre Gama
·
Updated Feb. 18, 18 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
16.4K Views

Join the DZone community and get the full member experience.

Join For Free

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!

CDI Lazy initialization

Published at DZone with permission of Alexandre Gama. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Introducing SmallRye LLM: Injecting Langchain4J AI Services
  • Injecting Implementations With Jakarta CDI Using Polymorphism
  • Extending the Power of Jakarta EE and MicroProfile With CDI Extension
  • Archiving Composition Over the Heritage With CDI Decorator and Delegator

Partner Resources

×

Comments
Oops! Something Went Wrong

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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!