EJB Dependency injection misunderstandings

When I’m doing interviews, I like to ask the following question (provided that the candidate has real life experience with EJBs):

There are two stateless session beans, A and B. A has a dependency on B; at what point can bean A use its injected (@EJB) dependency?

This turns out to be a tough question, as most people get it wrong. I’ve already heard a load of answers, but the most common ones are these: “anywhere if we use constructor injection”, “in the body of the business methods” and “the body of the constructor” (this is the most common one, actually). Let’s see how it really is, and why these answers are not (entirely) correct.

1.) Anywhere with constructor injection: Constructor injection is not possible with EJBs only; it is only available in JavaEE if you enable CDI (put an empty beans.xml file in your META-INF directory). That  is, however, a different story, so let’s skip CDI for this post. This means that we are left with enterprise beans only (@EJB injection style), in which case the following code will not work; it will not even compile, as the @EJB annotation is disallowed for constructors:

@EJB
public EjbA(EjbB ejbB) {
  this.ejbB = ejbB;
  // ...
}

public void doSomeWork() {
  ejbB.calculate();
  // ...
}

2.) In the body of a business method: Strictly speaking, this answer is not entirely wrong. Dependency injection would be completely useless if it was not available for business methods, so, this code will just work fine:

@EJB
private EjbB ejbB;

public EjbA() {
  // ...
}

public void doBusiness() {
  ejbB.calculate();
 // ...
}

Although this code is functional, the answer cannot be considered a good one, since a business method is not our earliest possibility to work with injected dependencies.

3.) The body of the constructor: let’s take an example. Consider the following code:

@EJB
private EjbB ejbB;

public EjbA() {
  ejbB.calculate();
}

Usually it is a bad idea to place any work in the constructor, but this is never truer than in our case. Surprise, this piece of code will not work, but throw a NullPointerException upon deployment. Why? Let’s see how EJBs are created by the container.

The EJB 3.1 specification mandates that every EJB has a public, default constructor (again, when CDI comes into play, this requirement is relaxed, but that’s a different story). The specification requires some pooling logic is present for Stateless and Message Driven Beans, (some containers will also pool Stateful beans too – even though it’s not required by the spec), so instances have to be created to populate the bean pool. In order to achieve that, the container reflectively calls the public, default constructor. By the time the constructor has completed, there is nothing injected into the EJB. From DI perspective, at this point our EjbA bean is just a simple, normal Java object, and its state is the very same as it would have been if we had instantiated it using the new operator.

As soon as the construction is complete, the magic kicks in and the container starts injecting all the dependencies the EJB has. After that process is finished, a construction finished event is fired; if the bean is registered for this event -e.g. it has defined a @PostConstruct method -, the container will call this method, which turns out to be the very first point in the lifecycle of an EJB, where any of the injected EJBs are available.

In short, the @PostConstruct lifecycle callback method is the answer to the question. That is the first point where EJB B will be available to EJB A. Trying to reference those dependencies any sooner will result in a NullPointerException.

Advertisements

Aspects for good, decoupled design

Basics

We’ve all learnt that good, object oriented design is based on some kind of layering of the concepts; one layer has a very well defined scope, like for example database access, presentation and the alike. A layer is not allowed to use any other layer, but the one and only the one  right below it. A typical such architecture would look something like the one on the following diagram (drawn with creately.com):

layer
Typical layered architecture

Every class to be written, is perfectly contained in one and only one layer. For example, the class UserDataConverter would probably be contained in layer “Data Conversion”; it has nothing to do with data access, for example, nor with displaying information.

The situation, however, gets completely different when dealing with requirements that are all over the system – like transactions or logging, for example. These things are spread in an application. They are not tied to a specific layer, but rather to all of the layers. If you want transaction management, that will possibly impact all the layers from the top to the bottom; you can’t do it in the DAO level alone. A transaction may start with a click on the GUI, and propagate all the way down to the database – should anything go wrong at any level, the transaction rolls back.

Let’s take an example: we want to perform some profiling, to measure the running time for some of our methods. These methods are not specific to any layer, they can be anywhere in our system, from the data access layer up to presentation. If we’d represent this feature on the diagram above, it could look something like this:

asp
Profiling feature breaks the boundaries of layers

We cannot say that profiling should apply to business logic alone, as we may as well want to know how many time does it take to convert data between different formats. Now, a very bad solution to this problem would be getting the current time in the beginning and the end of every method we want to be profiled, and doing something with the result. This solution would create some awful spaghetti code with lot of duplication, not to mention the tedious work one should be doing for a large, legacy system with hundreds of methods to be profiled.

A nicer option would be creating some kind of utility class, to which you could tell that the method has started executing, and has finished eventually. The utility would take care of computing the elapsed time and handling the resulting numbers. However, this would still be pretty tightly coupled, with two invocations per method.

public void longRunningMethod() {
  profiler.methodStarted();
  // ...
  profiler.methodFinished();
}

It may seem that we’ve now got rid most of the code multiplication, but those start/stop methods are still spread all around our code base. How do we clean up our code, then?

Aspects to the rescue

Thank God, there is a way to handle this situation (and of course not only this one; it’s also suitable for error handling, self-* operations, customized access management, and almost any feature that spans through layers): using aspects (as we will see, aspects are also called interceptors in some frameworks).

In order to understand how aspects actually work, let’s begin with examining method calls. A usual method call looks like this (obvious diagram to follow):

call
Ordinary method call

With the usage of aspects, this is slightly changed. The object on which the method is called, will be coated in a proxy object to which all the method calls will be routed. Whenever a method call is made to the proxy object, the call will be ‘hijacked’, and the proxy will be given a chance to perform different operations before, after or around (before+after) the method call. For this to work, you will need some kind of a container (either Spring or JavaEE can be a good choice) or third party library, as you cannot do this with Java right out of the box.

As you can see on the diagram above, the container directs the call of otherMethod to the proxy around object2, and performs some operations before and/or after the original method call. This way object2.otherMethod can always stay the same, the only things that change are the before and after methods, but as you are going to see, they are present at only one place within the whole system. The class that implements the logic for before and after is called the Aspect.

With such an aspect, the code for measuring elapsed times for methods can be totally decoupled from the rest of the application. We can come up with an aspect to hold logic that will be run around (remember, around = before+after) the method call:

public class LatencyTracerAspect {
    //...
    public void interceptAround() {
      //code for getting start time
      // run original, business method
      //code for measuring elapsed time
    }
}

All that remains, is to make the container notice our aspect, and tell it what methods to intercept. This is, nevertheless different for each and every container – see below for examples.

Simple, elegant, 100% reusable and totally independent of the business logic (single responsibility principle for the win).

 

Ups and downs of aspects

As mentioned earlier, aspects are very useful when some application requirements would break the boundaries of different layers. In these cases it’s best to organize these features such a way they are easily accessible everywhere, without code duplication – through aspects. However, it’s a very bad practice to extract pieces of business logic into aspects. A poorly implemented aspect with surprising side effects can be the best place for bugs to hide. It is perfectly OK to implement an aspect to check whether a certain XML file is well formed or not, before starting to work with it, but do not send back a reject message to the client from the aspect if the validation fails. Throw an unchecked exception instead, and let business logic handle functional requirements like sending reply messages.

Usually, using before or around aspects you can manipulate the parameters passed in to a method call; with after and around aspects you can modify the return values of the those methods intercepted. Even if it’s technically possible, (most of the times) it is not a good practice to do so. Again, figuring out that the system is throwing exceptions just because some aspect keeps changing the input parameters or the return values is, well, at least tedious and frustrating.

Don’t overuse aspects. Although many times they come in handy, they can make debugging a nightmare. Not to mention that normally aspects will not run with the unit tests suite (as there is no container present to interpret them), so watch out for logic hiding in them. Test them as well as your regular business objects.

 

Examples

As we know the theory by now, let’s apply this knowledge in practice. The code examples to follow are not meant to make you an aspects/interceptors expert, just to exemplify how the things mentioned above can be achieved with different containers. In the following, we are going to implement the profiling aspect using three different containers: Spring, EJB and CDI.

Spring

In Spring, each method to be intercepted should be contained in a Spring bean (note that only managed beans will be intercepted, not those created with the new keyword), and the same is true for the caller method. You cannot intercept a method call on a non-Spring-bean.

We are going to create an annotation, through which we will tell the container that we want our method intercepted. For this, we create a usual, nothing-fancy annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Profiled {

}

That’s it, the signaler annotation is done. Now, we shall create an aspect, and bind our annotation to it.No rocket science here, all we have to do is type in the following code:

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class ProfilingAspect {

	@Around("@annotation(Profiled)")
	public Object intercept(ProceedingJoinPoint context) {
		Object retval = null;

		long start = System.nanoTime();

		try {
			retval = context.proceed();
		} catch (Throwable t) {
			// Some clever exception handling
		}

		long end = System.nanoTime();
		System.out.println("------------------------------");
		System.out.println("Profiling result: " + (end - start) + " nanos.");
		System.out.println("------------------------------");
		return retval;
	}
}

Notice the @Aspect annotation at the top of of the class. Don’t fall in a common trap here: in your config file, you still have to define this aspect as a bean; thus the @Aspect annotation alone is not enough. Also, in the config file (I am taking a stand on Java class based configuration) you have to enable AspectJ style proxying, using the  @EnableAspectJAutoproxy annotation. Finally, don’t forget to call proceed() on the context object, so the program flow can advance.

Also note the @Around(“@annotation(Profiled)”) annotation. The expression (aka Pointcut) tells Spring to intercept all methods annotated with @Profiled. So, let’s create a method that can be intercepted (probably the easiest part):

public class Intercepted {
	@Profiled
	public void sayIt(String name) {
		System.out.println("We're happy, " + name);
	}
}

Pretty simple, huh? From now on, every method annotated with @Profiled will be intercepted by the container, provided that these annotations are placed on managed beans’ public methods.

Note:

  • The container will not intercept private method calls.
  • Don’t forget to put aspectjveawer.jar on your classpath.
  • You can play around with the context object; you can even change what’s getting passed and returned from a method.
  • Method calls from within the same bean are not intercepted
  • You can read further on this topic here

JavaEE

EJBs

(Aspects are called Interceptors in the enterprise world) In this case, the implementation for the profiler is somewhat easier. As this is JavaEE, you don’t have to place different kinds of jars on the classpath, as your container will have everything needed – right out of the box.

We don’t have to create annotations here, as the binding is solved differently with EJBs. Our interceptor class is somewhat similar to the one before, and looks like this:

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class Interceptor {

	@AroundInvoke
	public Object intercept(InvocationContext context) {
		//Logic is the same as before...
	}
}

The binding in the EJB code is done using the @Interceptors annotation applied on EJB class level(in which case all public methods will be intercepted) or method level(only those annotated methods will be intercepted). Our intercepted bean/method will be nothing more than:

import javax.ejb.Stateless;
import javax.interceptor.Interceptors;

@Stateless
// @Interceptors(Interceptor.class) could have been declared here too
public class Intercepted {

    @Interceptors(Interceptor.class)
	public void sayIt(String name) {
		System.out.println("We're happy," + name);
	}
}

Note:

  • Internal method calls (within the same bean) are not intercepted, no matter how the methods are annotated.
  • Private methods (resulting from the bullet above) are not intercepted
  • You are free to have several interceptors for the same bean/method. Those interceptors have to be enumerated like this: @Interceptors({Interceptor1.class, Interceptor2.class})

CDI interceptors

In the case of CDI interceptors we need an intercepted bean, an interceptor, and an interceptor binding – which is just like in case of our Spring example, a custom annotation.

With the help of Interceptor Bindings, we can tell the container which methods should be intercepted. The interceptor binding is not much different from our first @Profiled annotation; we only need to add @InterceptorBinding to it:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.interceptor.InterceptorBinding;

@InterceptorBinding
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Profiled {
}

An interceptor will be annotated with @Interceptor as well as the annotation dealing with the interceptor binding – it is somewhat similar to a Spring pointcut.  This will bind our @Profiled annotation to the interceptor logic:

import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;

@Interceptor
@Profiled
public class CdiInterceptor {

	@AroundInvoke
	public Object around(InvocationContext context) throws Exception{
        //... Logic same as before ...
    }

The intercepted class is, again, the same as with Spring:

	@Profiled
	public void sayIt() {
		System.out.println("CDI bean for the win");
	}

Finally, we have to enable CDI and the interceptors too. By default, CDI is turned off, you can switch it on by placing an empty beans.xml file in your META-INF directory. This is not enough in our case, though. CDI interceptors are also disabled by default; in order to enable them, we will make our new interceptor class visible to CDI container using the same beans.xml:

<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
                         http://java.sun.com/xml/ns/javaee
                         http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">

	<interceptors>
		<class>blog.intercept.CdiInterceptor</class>
	</interceptors>
</beans>

To read more in depth about CDI interceptors, go to: http://docs.jboss.org/weld/reference/1.0.0/en-US/html/interceptors.html.

Note:

  • Internal method calls (within the same bean) are not intercepted, no matter how the methods are annotated.
  • Private methods (resulting from the bullet above) are not intercepted

 

Conclusions

Aspects can be a very efficient and clean means of decoupling business logic from omnipresent features. This way the business methods can deal with business requirements while aspects add the decorator functionality for handling common, non-layer specific tasks.

Aspects are easy to get started with, as chances are high that larger systems are already based on either Spring or JavaEE. They both handle aspects (interceptors) very well, without writing complex code to enable them.

Aspects over-usage can have a bad impact on the system, as it can become hard to track what feature is handled by what aspect. Also, take care not to implement features carrying business value as aspects.

OCE EJBD 6 (1z0-895) Experiences

Today, I would like to share my experiences regarding the certified EJB exam, as I found little information on this topic while preparing for the certification.

Readings

In order to reinforce my knowledge, I’ve started with Enterprise JavaBeans 3.1. I think this book is great, it contains clear explanations, code snippets to support theory, common pitfalls (even testing EJBs) and so on. This book is not too hard to read; one can finish it within a week (even earlier, if you are familiar with the EJB related concepts – and have enough time). Nevertheless, the content of this book (in my opinion) is not enough to pass the exam. Well, it may be enough to pass, but in order to get the big picture, it is recommendable to read the whole EJB 3.1 specification (it’s right here). Now, believe me when I say that this whitepaper is boring as hell. Especially on the evenings, after a working, day, well, it seemed a challenge to me.

Someone on a forum I don’t recall, recommended this other book, Head first EJB. I personally think it’s a real bad idea to read that one, as it covers EJB 2.x which (thank God) looks nothing like EJB 3.x. It’s a waste of time, you can safely skip that.

Mock tests

Usually I am not in favor of buying testing frameworks; I can always dig up some mock tests to practice with (this was the case for both OCPJP and OCMJEA). I don’t really like to pay for something that’s right there on the internet (of course you have to be selective; not everything out there has any added value).

However, for this exam there are no free mock tests available. At all. Not a single one. You can find one or two pdf files with like 5-10 questions (usually of really poor quality) with a remark on the bottom that you can buy the complete dump for just seven million bucks. I don’t know whether the full versions are that untrustworthy too, I did not take the risk of buying them.

After two or three weeks of pointless chase after free smple questions, I’ve changed my mind and bought this software . Of course I checked out the trial version first, which just convinced me. The good news is that the full version costs only ~20$ – which is pretty cheap, I guess. It’s got more than 300 quality questions – grouped into categories like easy, though and “real brainer”. One or two of these questions even showed up at the real exam.

I don’t say that it’s a must to buy this or a similar testing tool, but…, well you should.. The EJB related topics are so huge, there are so many things to remember (annotations, xml tags, packaging etc.); it’s definitely worthy to do some practicing before sitting for the exam.

I personally failed the practice and the first mock test, so I am glad I made this investment. Questions can be tricky sometimes, but you will get used to it after seeing 20-30 of them. Anyways, they are tricky on the exam too.

The exam

was not too hard having answered all the 300+ mock questions. Nothing new showed up, I could answer (almost) all the question types with confidence.

Summary

In order to pass this exam you have to read (and memorize) a lot. It takes practice (both coding and answering questions) to score well, as the material is enormously big.

It took me 1.5 months to prepare (was only learning after work and on the weekends) but my previous EJB experience (of several years) helped me move a bit faster.

 

JavaEE dependency injection – common mistakes

In this post, I will cover some common mistakes people make when it comes about injection in enterprise environment.

1.) @EJB and the new keyword

I’ve seen dozens of forum posts, was asked the question so many times: “Instead of injecting my dependencies, the container throws a NullPointerException. Why?”

Most of the times, the answer to this question is really simple: because you are instantiating your EJB with the new operator, and don’t let the container do its job. For example, let’s consider the following piece of code:

@Stateless
public class Car {

  @EJB
  private Engine engine;

  //...

  public void startEngine() {
    engine.start();
  }

  //...
}

@Stateless
public class CarSalon {

  //...

  public void testDrive() {
    Car car = new Car();
    car.startEngine();
    // ...
  }
}

You see both classes here are stateless session beans; however, if you tried to run the code above, you’d get a big fat NullPointerException. The reason is that the object Car is not managed by the container, even if it’s a session bean. When you use the new keyword, you get in charge for managing that object. An object instantiated this way is outside the reach of the container, and it has no way of injecting dependencies. None of the @EJB, @Resource, @PersistenceContext etc. injections will have any effect. Simply put, using new you can only create POJOs, not Enterprise Java Beans.

In order to fix this error, you have to get the container take care of the Car object. Nothing easier than that, we just have to either look up the bean tgrough an instance of the InitialContext class:

@Stateless
public class CarSalon {

  //...

  public void testDrive() {
    InitialContext context;
    try {
		context = new InitialContext();
		Car car = (Car)context.lookup(CAR_JNDI_NAME);
		car.startEngine();
		//...
    } catch (NamingException e) {
        //...
    }
}

or, have the container inject the dependency:

@Stateless
public class CarSalon {

  @EJB
  private Car car;
  //...

  public void testDrive() {
    car.startEngine();
    //...
  }
}

Either way, the container will get you a fully initialized instance of the bean from the bean pool. And all the injections start working again.

2.) POJO injection

By POJO injection, we can mean two different things: injecting POJOs into Beans, or injecting Beans into POJOs.

Unless we are using CDI (which may be the topic of another post), we cannot inject a POJO into a session bean. You can only inject EJBs into EJBs. Intuitively, you cannot use the @EJB annotation to inject a POJO (as it is not an EJB), also, you can only look up EJBs using the InitialContext (as POJOs have no JNDI names). In one sentence, without CDI you cannot inject POJOs anywhere.

The other way around, is possible, though. You can use a fully initialized EJB in your POJO code. The @EJB annotation will not work, as only an EJB can be injected into another EJB using annotations. However, your object needs not be an EJB to be able to use the InitialContext.lookup() mechanism (provided that there actually is a container running under your application).

Note that starting from EJB 3.1, JNDI names are standardized. If (using the example above) we suppose that we have an EAR called Salon_EAR amd an EJB project, called Salon_EJB then the JNDI name for the object Car is:  java:global/Salon_EAR/Salon_EJB/Car.

3.) EJB injection and constructors

This one is related to Glassfish(3.1.1) application server and perhaps several others (some other app servers may support this, but Glassfish is the reference implementation, so…)

Let’s get back to the car salon example above. Given this piece of code:

@Stateless
public class CarSalon {

  @EJB
  Car car;

  public CarSalon() {
    car.startEngine();
  }

  // ...
}

Surprisingly enough, this code will throw a NullPointerException in deploy time. The Car object injected using the @EJB annotation is not available in the constructor. And no, it’s not because CarSalon is created first and Car second (you can even annotate the Car class with @Startup to be sure about the initialization sequence).

What is the solution then? Is there no way of using container managed objects in the object initialization process? There is, fo course. Let’s move all the logic from the constructor into a @PostConstruct method. The code now looks like this:

@Stateless
public class CarSalon {

  @EJB
  Car car;

  public CarSalon() {
    System.out.println("Constructor");
  }

  @PostConstruct
  public void init() {
    System.out.println("PostConstruct");
    car.startEngine();
  }

  // ...
}

And guess what, this actually gets deployed. The post construct block will run as part of the initialization process, but still outside the constructor. It even makes your code cleaner since we all know that it is not a good idea to place work in the constructor. Not to say that all the injected resources are available in such methods.