How to customize dependency injection


I often explain particular features of JSE but not JEE possibilities.
Today we’ll see how to make a custom injection with JEE.
This feature is not directly supported by JEE but with defaults interceptors it becomes possible.
The Steps are :
1/ Create the annotation which will be used to tag a member instance to inject.
2/ Write a default interceptor which acts at post construction. It must check if the annotation exists, and thanks to reflexion set the value.
3/ Use the annotation with your EJB.

Annotation definition :

public @interface InjectedValue { }

Interceptor implementation :

public class CustomInterceptor {
    public void inject(InvocationContext invocation) throws IllegalAccessException {
        Object o = invocation.getTarget();
        for (Field field : o.getClass().getFields()) {
            if (field.isAnnotationPresent(InjectedValue.class)) {
                boolean previousAccessibility = field.isAccessible();
                try {
                    field.set(o, 42);
                } catch (IllegalAccessException e) {

Interceptor declaration :


Using of the interceptor :

public class MyEJBBean implements MyEJBRemote {
    private int myValue;

Dependency injection is the foundation of IOC (Inversion of control) and with interceptors you can write your dependency injections.
Defaults interceptors are applied on all EJBs, but if you want, you can attach interceptor to a particular EJB.
With AOP (Aspect Oriented Programming), and thanks to pointcuts, you can precisely identify a method signature and act on it.
We’ll maybe see that later.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s