News Ticker

Context Dependency Injection

The Java EE programming model has been simplified substantially since J2EE. Annotations have replaced the XML description files, convention over configuration have replaced the tedious manual configuration and dependency injection hides the creation and lookup of resources.

Resources are created and injected at injection points marked by annotations such as @Inject. All you need is a POJO that meets all of the conditions of the managed beans specification JSR 299 and depending on the annotation used it will become an EJB, servlet, singleton or RESTful web service.

The object is injected by the container and is determined by type. However using an interface as a type can confuse the container if there is more than one concrete implementation. It doesn’t know which object to inject. This confusion can be resolved by the use of a qualifier annotation that marks the concrete implementation you want to implement. We will see how this annotation is used with @Producer in the implementation of the factory pattern. Beans or objects that you want to inject that do not conform to JSR299 use the @Producer annotation to make them injectable.

JSR 299 Managed bean specification

  • It is not a nonstatic inner class.
  • It is a concrete class or is annotated @Decorator.
  • It is not annotated with an EJB component-defining annotation or declared as an EJB bean class in ejb-jar.xml.
  • It has an appropriate constructor. That is, one of the following is the case:
  • The class has a constructor with no parameters.
  • The class declares a constructor annotated @Inject.
  • No special declaration, such as an annotation, is required to define a managed bean.

To enable CDI you must have a beans.xml file in your project (under the META-INF or WEB-INF).

What Next

If you are interested in learning more about Java EE, why not check out my new course here, you can even start with a free trial. Also check out my other articles on the Observer PatternDecorator PatternSingleton PatternFactory Pattern, and the Facade Pattern.

Leave a Reply

%d bloggers like this: