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!
 

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


1 + eight =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
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.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books