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.

implIn 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!

DI / CDI – Basics


Introduction (DI/CDI Basics)

First of all, I would assume there is a bit of confusion to this, but the truth of the matter is, they are just the same – the difference is that usage and its purpose.

DI (Dependency Injection) is the general term  – this feature is basically the one doing the bean discovery and bean wiring process on any application. Its not just you use it in your application, you can also use it in your unit tests and mocks. Of course, there are a lot of DI frameworks out there, you have: Guice, Seam, Spring (Seam and Spring extended the DI scheme and made their own), EJB 3.x and CDI itself.

CDI on the other hand, combines all this technology and introduce a lifecycle to the components – this allowed unification of DI technologies to making development of new features straight forward and mostly doable; you can combine Seams lifecycle mappings with Spring MVC with JPA as its persistence layer – these technologies were all created separately yet with CDI, application developers can combine them to create and development JEE application.

I will need to break down the topics as I would definitely bore everyone with words and letters here so:

  1. DI / CDI Basics
  2. Basic Injection
  3. Qualifiers, Scope
  4. DI / CDI Advance

I will be creating separate posts for each!

Lets Begin! 

SPI (Service Programming Interface)

It also has this so called SPI – apparently a feature set along with API, but has a different purpose entirely.

  • The API is the description of classes/interfaces/methods/… that you call and use to achieve a goal.
  • The SPI is the description of classes/interfaces/methods/… that you extend and implement to achieve a goal.

With SPI, you can actually extend the JEE6 to create a different framework of your own, showcasing portability, and extensibility. (But I’ll dive into that later).

Why CDI for JEE6?

CDI has been around in JEE5 (J2EE) and has been a major success. A lot of new development benefits from its approach that ultimately simplifies the overall development process. Several reasons why CDI was improved in JEE6.

  • JEE5 do support resource injection, but it still lacks a general purpose dependency – it only supports @EJB, @PersistenceContext, @PersistenceUnit, @Resources) – of course this is with the exception of Spring that introduce different annotations for managing bean lifecycle
  • Non-type based injection (and weak)  – String name and XML injection is really fragile. Improving type-based injetcion enables better tooling in general.

Terminology

CDI – Context and Dependency Injection

Weld

  • JSR 299 reference implementation – reference implementation is the SPI used to etxend a JSR specific implementation.
  • Provides extended CDI support for Servlet Container.
  • CDI enhancements for extension writers.
  • Maven Archetypes for CDI and Java EE (I love maven!).

CDI Theme: Loose Coupling and Strong Typed

Loose coupling simply means objects is loosely independent to the objects that uses or currently using them. CDI introduces new features for decoupling such as qualifiers, enhances interceptors, decorators, message producer, consumer and its underlying events mechanisms. Will dive further in to each example on the advance topic of CDI.

Strong Typing – simply means that strict declaration of beans by letting the container create and map specific names to objects. This eliminates the need to do string based naming of beans, casting almost not needed since the casting is done by the container (by taking advantage of qualifiers).

Bean (What is it?)

There are technically many form of beans, you have: JSF Bean, EJB Bean, Spring, Seam, Guice CDI, Entity Beans, etc – but ultimately, beans are just POJOs that has special definition – definition that was defined by the Managed Bean 1.0 – specification made in Java EE6. What does this mean is that any POJOs can be any type of bean, as long as it complies with the specification standards – further simplifying the declaration and development process. The container does the work for managing the POJOs and will add support for it by giving / introducing common basic services such as:

  • Lifecycle Management (@PostConstruct, @PreDestory)
  • Injection of a resource (@Resource)
  • Interceptor (@Interceptors, @ArounInvoke)
@javax.annotation.ManagedBean
public class MyPojo {

@Resource   // Resource injection
private Datasource ds;

@PostConstruct  // Life-cycle
private void init() {
   ....
}  
@Interceptors(LoggingInterceptor.class)
   public void myMethod() {...}
}

With this in mind, what about EJBs, RESTs and CDI beans?

  • EJB bean service – managed bean, with the common services (above) and support for Transaction, security, thread safety and persistence.
  • REST bean service – managed bean with HTTP support
  • CDI bean – managed bean with lifecycle supports:
    • Auto discovery
    • Qualifiers
    • Scope
    • EL
    • Interceptors and Decorators
    • Alternative bean (by Qualifiers at runtime)

To put it into perspective, Manage Bean is ultimately an SPI that was extended for specific use. EJBs, Rest, Entity beans are all Managed Beans – but with additional services from the container. Thus, if you define a POJO with a @Stateless or @Stateful annotation, the container automatically detects that its an EJB bean and it needs container specific support like transactions, security, thread safety, extensions etc.

package mypackage;
import javax.ejb.Stateless;

@Stateless
public class GreetingBean {
  public String greet(String name){
      return "Hello " + name;
   }
}

A simple POJO class turned into a Stateless bean with just a flick of finger (actually typed in) that resulted to that one liner @Stateless code. Unlike how EJB was defined on the priori 3.x (such a pain).

Download the sample (above) from here: Click me

Automatic Bean Discovery

The CDI container is the one responsible for how the beans are discovered, but how does it do it?

  1. It first scan the classpath that contains both application and container archives.
    1. It tries to scan through the classpath and see what POJOs are tag for discovery – that is, Managed Bean. You can think of it that it puts in a pool and can readily available when another Managed Bean calls it thru injection (more on that on next blog topic)
  2. Then it detects presence of beans.xml (or any context xml file definition).
    1. For Spring fans, this is much like an applicationContext.xml (at least thats the convention, but loose) – you pass that xml on the contextConfiguration listener (thru parameter) and Spring CDI Container will automatically tag objects (beans) in it for discovery – of course you need to define scanning mechanisms (component-scan).

Ultimately, DI / CDI was introduce to simplify the development process, unify the technologies and overall to produce a more robust, extendible application. Letting all the container do the work in terms of tagging the common services of the bean makes the developer task easier and more over avoiding pitfalls as a result of previous frameworks. SPI – is really the definition of improvement here, allowing the actually JEE6 framework to be extendible creates a more dynamic nature – business application architects can now design their own framework and conventions. Put more business specific designs or annotations for their own rules and give the robustness and flexibility that is always required for enterprise application.

Next Topic: Basic Injection – I don’t want to put everything in one post, so I’ll leave it up to you to absorb first and check the sample I created. From here on now, I’ll tackle more on the examples of DI and CDI.

JEE6 – Servlet 3.0


Servlet 3.0 – has a bunch of ground breaking features that will ultimately change how developers will code and write JEE Web Applications – some might say that its conventions defy most of our understanding about how things “should” work in theory but thats one of the beauty of innovation and continuous improvement; challenging the convention and give a better and efficient solution.

Topics covered in this blog post:

  1. Ease of Development – what did change?
  2. Dynamic registration of Servlets and Filters
  3. Pluggability
  4. Resources in bundled jar files – A new feature called Web fragments.

Ease of Development

This is one of the subjective topics in world of JEE Development – its not about drag and drop all the time, its about how you can further refine your way of development that complies to standards, optimal and strictly checked across conventions.

Declarative style of programming through annotation – In JEE6, the web.xml is now optional and all POJOS can now be tagged thru use of Annotations. You can declare Servlets, Filter, Listeners, Init Params, etc – almost everything that is under the web.xml can now be configured thru use of annotations.

  1. @WebServlet – Define a Servlet
  2. @WebFilter – Define a Filter
  3. @WebListener – Define a Listener
  4. @WebInitParam – Define init params
  5. @MultipartConfig – Define file upload properties
  6. @ServletSecurity – Define security constraints

Note: Although, this can be done, developers can still use the web.xml to override these values.

I attached an example here for you to test.

Dynamic Registration of Servlets and Filters

Another feature available is Dynamic Registration – Performed during ServletContext initialisation:

public class TestServletContextListener
             implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {

        ServletContext servletContext = sce.getServletContext();

        ServletRegistration.Dynamic dynamic =
                   servletContext.addServlet("DynamicServlet","com.mycom.MyServlet"); 
        dynamic.addMapping("/dynamicServlet"); // URL mapping
        dynamic.setAsyncSupported(true);
    }
}

and of course, you can look up and hook the dynamic servlet / filter

ServletRegistration declared = ServletContext.getServletRegistration("DeclaredServlet");
declared.addMapping("/declaredServlet");
declared.setInitParameter("param", "value");

Download the maven project here.

Pluggability

Enable use of 3rd party framework without boiler plate configuration in deployment descriptors. Modularize web.xml to allow frameworks to be self-contained within their own JAR file and Programmatic configuration APIs Use of annotations.

The motivation behind pluggability is to decrease the complications of putting all configuration in one single sile (web.xml) if a specific framework is needed. For example, if a developer needs Spring support for an existing Web Application – the 1st thing to do is put in the servlet/ listener for Spring as part of it support – it can get ugly when in the future, a new EE technology arises as you need to put everything again on the web.xml file.

Now with JEE6 – you can create a sub-project with a web-fragment.xml that will mimic a section on the main web.xml – this allows further improvements (or pluggable functional requirements) to be independently created and isolated. Below is an example of a web-fragment.xml

<web-fragment>
  <servlet>
    <servlet-name>welcome</servlet-name>
    <servlet-class>com.mycom.WelcomeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>welcome</servlet-name>
      <url-pattern>/Welcome</url-pattern>
  </servlet-mapping>
  ...
</web-fragment>

It is closely / very similar to web.xml.

Download the Sample web-fragment project here.

Resources in bundled jar files

  • Static and JavaServerTM Pages (JSP) resources no longer confined to web application’s document root
  • May be placed inside WEB-INF/lib/ [*.jar]/META-INF/resources
  • Container must honor this new location when processing HTTP requests and calls to ServletContext#getResource or ServletContext#getResourceAsStream  methods
  • Resources in document root take precedence over those in bundled JAR files, however.

javaee6_servlet3.0_basics__1_.pdf__page_29_of_32_

Given the web-fragments and the new resources bundle jar support – functional requirements that requires end to end processing can now be developed separately from the main parent application.

The new and improve Servlet 3.0 brings a lot of effective tools that will allow developers to create more quality and robust applications with the platform.  Annotation / Declarative programming – takes the descriptors to new heights as Servlets, Filters and Listeners can now be done on the Java Code level. Dynamic Registrations of Servlets, Filters, Listeners etc can be used to create JIT pojos that will handle specific business cases, DI and CDI support allows developers simplify the paradigm by simply letting the container take care of how the objects are made and the best of them all, web-fragments and support for resource bundle jar gives a different separation to the development as it allows isolation of functional specific – web project, leveraging JEE existing technologies without having to deal with a lot of configuration thru the parent web application.

A Brief Overview of JEE6


J2EE has come a long way since its birth. It has evolve to a sub-par platform to an all globally renowned standard. Now, JEE6 the latest major specification for JEE platform has gone leaps and bounds to further enhance its capabilities as well as introduce more effective and efficient specs on the developers table, without compromising the standard capability that makes Java Web Applications durability stands on the tests of time.

javaee6_overview_short__1_.pdf__page_2_of_9_

Major Features of JEE6 – Though as a developer, what did change and how?

Right sizing: Profiles and Pruning

By introducing Profiles – technical architects / developers can control the APIs / Specs needed for the application. Java / JEE is a huge platform and imports a lot of apis to projects. Profiles is an introductory concept to limit the number of APIs needed for a specific application. For example: In a Web Application  (Web Profile), you need support for JSP, EL, JSTL, JSF, EJBs (backend) etc. This wouldn’t be the same APIs and SPECs for J2ME right or J2SE apps right? You wouldn’t need JSP support if you’re developing a desktop application or EL if you’r developing a J2ME app. The mission behind profile is use only what is necessary to build the application to optimally create and develop the implementation. One good pre-defined profile is the Web Profile that uses EJB Lite – trimmed down version of Enterprise Java Beans.

javaee6_overview_short__1_.pdf__page_5_of_9_

Pruning – is another feature for right sizing, allows removal of existing APIs or Frameworks being used by the application.  It provides a way to remove the following technologies from the platform.

  • Java EE technologies that are outdated and have been replaced by new sets of technologies
  • Technologies that are not well supported
  • Technologies that are not widely deployed

Extensibility – Plug-ability

Need other frameworks for your application? JEE6 has this plug-ability feature that will help developers ease their process of plugging in multiple frameworks to be used in their applications.  Not only its easy programmatically, doing so using Maven will ease it even more – by dependency management.

This mechanism provides a way to include additional technologies and frameworks that are not part of the standard platform. Extensibility points and Service Provider Interfaces (SPIs) help developers plug in these technologies to their platform implementations. Two new extensibility options are support for open-source enterprise application frameworks and scripting languages.

Ease of Development

Defaults over configuration – Profiles are set – why configure everything if there are pre-defined profiles that can be used? Idea: How about combining that with Maven Archetypes?

DI/CDI – Of course Spring is the master of Dependency Injection – but we’re in the open world, anyone can get the idea, create a new one an innovate it. Dependency Injection allows developers to class load POJOs using a one liner annotations. IoC scheme then uses these beans to inject them on any beans that are class loaded.

Specifications

The specs has come a long way, but the very foundation is still there. The more the specs improves, the better Java Development / JEE Development experience will be. After all the purpose of this specification is to simplify the things and stuff that works.

javaee6_overview_short__1_.pdf__page_8_of_9_

In this blog post, I showed the basics and powerful new features of JEE6 – next post, I’ll focus more on Servlets 3.0 and how it compliments or add up to the new platform.

Next Stop: Servlet 3.0 Basics!