Basic Injection / Qualifiers, Scope

This is a continuation of the DI/CDI Basics tackled last week  – in this post, I’ll be discussing Basic Injection, Qualifiers and Scope.

In our last topic, there we’re a great deal of information regarding the concepts of DI/CDI, we also discussed how these beans or class loaded using the annotations  -that makes up the composition of the object and created samples on how can we declare them programmatically. In this post, we will tackle more on the injection part, e.i how to acquire a certain resource and inject them on another resource for usage.

So how to inject a bean in the first place?
 

Basic Injection

How do you inject a Bean?

  • Use @Inject <Java-Type> <variable> for field injection
  • <Java-Type> can be Java class or Java interface
public class MyGreeter {
   // Inject Greeting object for field injection
   @Inject Greeting greeting;
   public sayGreeting(String name){
      // You can then used the injected Greeting object
      System.out.println(greeting.greet(name)); 
   }
}

Where can beans be injected?

Bean can be injected at “Injection points”

  • Field
  • Method parameter

Method can be:

  • Constructor (useful for created immutable object) > Initializer
  • Setter method
  • Producer
  • Observer
public class MyGreeter {
   private Greeting greeting;
   // Use constructor method injection
   @Inject
   public MyGreeter(Greeting greeting) {
      this.greeting = greeting; 
   }
   public sayGreeting(String name){
      System.out.println(greeting.greet(name)); 
   }
}

Qualifiers

Qualifiers are used to assign a specific bean if there are multiple implementation type (interface and child classes). Say you have two candidates (implementation class) for a specific interface:

  • Interface is Person
  • Class 1 is Regular Person
  • Class 2 is NonRegular Person

c_diagram_person

We can use Qualifiers to cleanly designate the implementation of classes by introducing / creating an Qualifier annotation of your own:

RegularPerson Qualifier Annotation:

p_qualifier

NonRegularPerson Qualifier Annotation:

non_reg_qualifier

Now we need to create an implementation class and tag it to the Qualifier we created.

RegularPersonImpl:

regular_impl

NonRegularPersonImpl:

non_reg_impl

Note: You can have as many qualifiers as possible – remember that Qualifiers are meant to separate logical objects implementation from its common interface.

Now that the implementation is set, we can now Inject the class and use its qualifier.

impl

In this example, you can clearly see the usage, by introducing a Qualifier, developer can clearly specify the implementation type by annotation.

Download the example here.

Other things you can do with Qualifiers?

I won’t be discussing further what else can you do with qualifiers, instead, I’ll give let you check this examples for you to try and explore:

Scope

Why in the first place we need Scope on our Objects? –  For Web applications, we need our beans to hold state over the duration of the user’s interaction with the application, for example, across multiple requests to the server.

There are 5 types of scopes that developers can assign to an object:

  • @Dependent (default)
    • The default scope if none is specified; it means that an object exists to serve exactly one client (bean) and has the same lifecycle as that client (bean).
  • @RequestScoped
    • State of an object is maintained during a user’s interaction with web application in a single HTTP request.
  • @SessionScoped
    • State of an object is maintained during user’s interaction with a web application across multiple HTTP requests.
  • @ApplicationScoped
    • Shared state across all users’ interactions with a web application.
  • @ConversationScoped
    • Conversation context is demarcated explicitly by the application
      • Spans multiple requests
      • But “Smaller” than session
    • Used when you want to have explicit boundaries of multiple conversations within a single session

I won’t be diving into the details here but what I’ll provide you are actual examples that you can run. Download the projects here.

Next Stop: DI / CDI – Advance

With this new features, you can clearly observe and imagine how it will improve developer productivity by simplifying a lot of processes to setup a Web Application – Qualifiers can be created to clearly separate logical / business beans with a common goal (by interface), scoping let developers control the flow and manage the state of objects – and the simplification of calling beans directly from the UI thru EL makes it more straightforward.

Please do check the samples and try them on your own, it would be better to check an actual example than by just reading thru the details and concepts. Enjoy!
 

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


9 × = forty five



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close