Understanding Dependency Injection – Part 2 PostConstruct and Constructor Injection

In the first part of this series I introduced basic IoC functionality. In this part we will cover @PostConstruct methods and Constructor Injection.

Consider the following scenario:

Since Car has to be instantiated prior to field injection, the injection point engine is still null during the execution of the constructor, resulting in a NullPointerException.

This problem can be solved either by JSR-330 Dependency Injection for Java constructor injection or JSR 250 Common Annotations for the Java @PostConstruct method annotation.
Continue reading Understanding Dependency Injection – Part 2 PostConstruct and Constructor Injection

Understanding Dependency Injection – Part 1 IoC

Dependency Injection, be it Spring IoC, CDI or Google GUICE is often seen as hard to understand or even referred to as “black magic”.

As with all complex frameworks the actual working basis is fairly simple and straight forward. In this series I am going to demonstrate, in a rather simplified manner, the internal workings of dependency injection frameworks by developing one from scratch, Voodoo DI.

Please note, Voodoo DI is meant SOLELY for educational purposes, if you are looking for production ready DI frameworks please look at CDI, Spring IoC or Google GUICE.

In this series I am going to concentrate on the annotation driven approach based on JSR-330 Dependency Injection for Java annotations used by all major DI frameworks.

JSR-330 Dependency Injection for Java specifies a common set of annotations that are used by Spring, Guice and CDI.

  • @Inject – defines injection points on fields, methods and constructors.
  • @Qualifier – A qualifier may annotate an injectable field or parameter and, combined with the type, identify the implementation to inject.
  • @Named – Similar to @Qualifier, it allows the identification of the correct implementation based on name and type.
  • @Singleton – Singleton scope, only one instance is created by the DI framework.
  • @Scoped – Used to define new scope annotations. The DI Framework may use these to define new contexts (e.g. @RequestScoped).

Continue reading Understanding Dependency Injection – Part 1 IoC

CDI Passivation Uncovered

Frequently there is confusion about passivation of contextual instances with CDI, especially when non-passivating scopes such as request scoped are injected in passivatable once.

The specification defines passivation (serialization) capabilities, allowing the container to free memory by transferring idle objects to secondary storage when required.

The temporary transfer of the state of an idle object held in memory to some form of secondary storage is called passivation.
The transfer of the passivated state back into memory is called activation.

CDI-Spec 1.2 – Chapter 6.6.1

CDI’s session and conversation scopes are the only build-in passivation capable scopes. Request and application scopes are not passivating capable. If a bean is defined with a passivating scope, it and all applied interceptors and decorators must be serializable (see CDI 1.2 Specification – 6.6.1. Passivation capable beans).

Passivation of Normal Scoped injections

When working with passivation capable scopes such as @SessionScoped, it is still possible to inject references to non-passivating scopes such as @ApplicationScoped. Application scoped beans are not passivation capable, however the injected dependencies are.

public class MySession implements Serializable {
  private MyAppData myAppData;

public class MyAppData {

Continue reading CDI Passivation Uncovered

Pushing ahead on Concurrency for Java EE 8

JSR-236 has only been a half-hearted attempt at bringing asynchronous operations to the wider Java EE context, leaving many gaps or even specification bugs depending on how you see it. As of now the Concurrency Utilities for Java EE specification remains closed for Java EE 8.

One of the more painful omissions being the rather ambiguously defined CDI context propagation. Tasks and Contexts and Dependency Injection (CDI)
CDI beans can be used as tasks. Such tasks could make use of injection if they are themselves components or
are created dynamically using various CDI APIs. However, application developers should be aware of the
following when using CDI beans as tasks:

  • Tasks that are submitted to a managed instance of ExecutorService may still be running after the
    lifecycle of the submitting component. Therefore, CDI beans with a scope of @RequestScoped,
    @SessionScoped, or @ConversationScoped are not recommended to use as tasks as it cannot be guaranteed
    that the tasks will complete before the CDI context is destroyed.
  • CDI beans with a scope of @ApplicationScoped or @Dependent can be used as tasks. However, it is still
    possible that the task could be running beyond the lifecycle of the submitting component, such as when
    the component is destroyed.
  • The transitive closure of CDI beans that are injected into tasks should follow the above guidelines
    regarding their scopes.

JSR-236 Concurrency Utilities for Java EE Version 1.0 FR

This specification leaves a lot of room for interpretation. The current consensus is that the spawning thread’s request, session and conversation contexts are not propagated to the asynchronous process. Furthermore the request context is not even activated for the asynchronous operation (see discussion “inheritance of CDI scopes” for more details).
Continue reading Pushing ahead on Concurrency for Java EE 8

Building extensible Java EE Applications – Part 2

The first part covered adapting and packaging extensible Java EE applications.

Introducing Plug-ins

This part will demonstrate how Java EE application can be extended via plug-ins.

To do so we will have to define Service provider interface(s) (SPI).

public interface CorePlugin {
  public String getName();

The applications SPI should be provided in a separate JAR decoupling plug-ins from the core application and avoid cyclic dependency issues (see the previous post for more details).
Continue reading Building extensible Java EE Applications – Part 2

Building extensible Java EE Applications – Part 1

With the advent of Java EE 6 it has become easier to build extensible applications. In this first post we will briefly explore how core components of standard applications can be customized with CDI @Specializes/@Decorator and more interestingly packaging the customized applications.


Specialization in Java EE allows for simple customization of existing beans via inheritance. If a @Specializes bean is found on the classpath it will be injected instead of the original.

The specializing bean has to extend the original bean, it inherits all qualifiers and its name, if defined with @Named.

public class CoreService {
    public void doStuff() {
        System.out.println("Default implementation is doing Stuff.");

public class MySpezializedService extends CoreService {
    public void doStuff() {
        System.out.println("Spezialized implementation is doing Stuff.");

MySpezializedService will be injected instead of MyDefaultService in any place where MyDefaultService has been defined for injection.
Continue reading Building extensible Java EE Applications – Part 1

Concurrency Control for CDI

At the moment there is no standard concurrency control mechanism for CDI managed beans, and at the time of writing it has not been taken into consideration for CDI 2.0 specification either.

The lack of any container based concurrency control, can lead to issues when working with unprotected contexts such as Application- or Session-Scoped beans.

Unlike EJB’s, where the container handles concurrency control, CDI only defines concurrency control for the conversation context.

The container ensures that a long-running conversation may be associated with at most one request at a time, by blocking or rejecting concurrent requests. If the container rejects a request, it must associate the request with a new transient conversation and throw an exception of type javax.enterprise.context.BusyConversationException from the restore view phase of the JSF lifecycle. The application may handle this exception using the JSF ExceptionHandler.
Conversation context lifecycle in Java EE – CDI Spec

Aside from this concurrency is only mentioned in conjunction with CDI EJB interaction.

Whilst all other relevant normal scoped contexts (Application- and Session- Scoped) are completely unguarded, the specification only defines a non adaptable concurrency control for conversation scoped beans. In my previous post on sychronizing access to CDI Conversations, I described how some of these limitation can be overcome.
Continue reading Concurrency Control for CDI

Stateful JAX-WS with CDI – Part 1

Usually it is desirable to keep web services stateless. This is because it allows for easier scalability (since no state has to be shared across multiple instances) and reduced load on system resources (as no state has to be held or cleaned up).

However, there are scenarios where it may be desirable to maintain server sided states across multiple requests. As I have demonstrated in my previous post CDI CONVERSATIONS FOR JAX-RS WITH JEE 6, it is possible to utilize CDI conversation scope in JAX-RS restful services. CDI conversation scope was designed to deal with the limitation of having one session per browser, allowing for tab-specific state to be kept on the server side.

JAX-WS is primarily used in fat-/smart-client server scenarios. Fat-/Smart-clients, unlike browsers, are capable of managing multiple sessions as required. JAX-WS has build-in support for SOAP and HTTP session management (see JAX-WS 2.2 Rev a, Chp. Session Management).

Setting up the session context on the server side is a simple matter of defining a @SessionScoped CDI bean…

public class Interactions implements Serializable {

  private List<String> names = new ArrayList<>();

  public String interact(String name) {
    final String interactions = "Hi " + name + ", I previously interacted with " + names;
    return interactions;

  public Integer getNumberOfInteractions() {
    return names.size();

Continue reading Stateful JAX-WS with CDI – Part 1

CDI VooDoo – The Bean Manager and Circular Injection

CDI supports circular dependency injection when at least one of the beans has a normal scope*, this may be useful when sharing contextual information between beans of same or different scope (e.g. MVC pattern).

The CDI BeanManager is responsible for the creation of all CDI beans and managing contextual access to all normal scoped beans.

public class Foo {
   private Bar bar;

public class Bar {
   private Foo foo;

Continue reading CDI VooDoo – The Bean Manager and Circular Injection

CDI 1.1/1.2 Im-/Ex-plicit bean archives

Implicit bean archive
CDI 1.1 introduced the notation of implicit bean archives, making the inclusion of beans.xml optional. Only beans annotated with bean defining annotations will be considered.

An implicit bean archive is any other archive which contains one or more bean classes with a bean defining annotation, or one or more session beans.
CDI 1.1 specification, 12.1. Bean archives

It is important to note that CDI 1.1 defined all JSR-330 javax.inject.* annotations as bean defining, however this caused some problems with archives that use other JSR-330 compliant injection frameworks, most notably google guava library.

The CDI 1.2 maintenance release addresses these by limiting bean defining annotations to:

  • @ApplicationScoped, @SessionScoped, @ConversationScoped and @RequestScoped annotations,
  • all other normal scope types,
  • @Interceptor and @Decorator annotations,
  •  all stereotype annotations (i.e. annotations annotated with @Stereotype),
  •  and the @Dependent scope annotation.

CDI 1.2 specification, 2.5.1. Bean defining annotations

Any bean that does not define at least one bean defining annotation, will be ignored by CDI. Most notably beans solely defining @Named or CDI pseudo-scopes other than @Dependent, such as @Singleton will be ignored.
Continue reading CDI 1.1/1.2 Im-/Ex-plicit bean archives

Do NOT follow this link or you will be banned from the site!