How to customize dependency injection

Hi,

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 :

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
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();
                field.setAccessible(true);
                try {
                    field.set(o, 42);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                field.setAccessible(previousAccessibility);
            }
        }
    }
}

Interceptor declaration :

<interceptors>
    <interceptor>
        <interceptor-class>ejb.CustomInterceptor</interceptor-class>
        <post-construct>
            <lifecycle-callback-method>
                inject
            </lifecycle-callback-method>
        </post-construct>
    </interceptor>
</interceptors>

Using of the interceptor :

@Stateless
public class MyEJBBean implements MyEJBRemote {
    @InjectedValue
    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.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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