Do You think there is Magic With Dependency Injection in java ?

I will explain after i’ve watched a video of Adam Bien   showing how does DI Work

We Will Use Java reflection  and Annotation to understand well how this magic work

  • First step :we should create our injector annotation and call it  InjectAnnotation
package coffeecode.test;

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

/**
 * Created by CoffeeCode on 2/22/17.
 */

@Target(ElementType.FIELD)// what can be annotated -> i choose fields only
@Retention(RetentionPolicy.RUNTIME)// by reflection mean at Runtime
public @interface InjectAnnotation {
}
  • second step : Create the Facade class ( the class which will be injected like EJB  facade, CDI  or any BO class .. )
public class Facade {
}
  • Third step : Create Our Controller class
package coffeecode.test;

/**
 * Created by CoffeeCode on 2/22/17.
 */
public class MyController {

    @InjectAnnotation
    Facade facade;

    @Override
    public String toString() {
        return "MyController{" +
                "facade=" + facade +
                '}';
    }
}

  • Final step: Create the main class and inject the facade
package coffeecode.test;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * Created by CoffeeCode on 2/22/17.
 */
public class MainTest {


    public static void main(String[] args) throws ClassNotFoundException, 
IllegalAccessException, InstantiationException {
//full class Name ( package.class)
        Class<?> clazz= Class.forName("coffeecode.test.MyController");
        Object myController=clazz.newInstance();
//get all Fields from myController Object
        Field[] fields = clazz.getDeclaredFields();

//search for the field which have annotation = InjectAnnotation
        for (Field field:fields){
            if(field.getAnnotation(InjectAnnotation.class)!=null){
//create new instance of facade
                Object facade=field.getType().newInstance();
//and set associate it to  myController
                field.set(myController,facade);// AND BOOM 
            }
        }
        System.out.println(myController.toString());
    }
}


the result will beMyController{facade=coffeecode.test.Facade@1d44bcfa}

Please If you have any feedback say it

Advertisements