Wednesday, June 25, 2014

Type safe dependency injection using Java 8.0

So I sometimes really miss old school Dependency Injection. Back when Spring was still "lightweight" we happily configured all our beans in an application.xml file with the "learn-in-a-day" Spring bean xml configuration. The downsides to this were of course a loss of type safety. I can think of quite a few test cases whose sole purpose was to bootstrap the Spring configuration file and just see if the ApplicationContext starts up without going belly-up due to mis-wiring and correct resolution of included bean xml configuration files.

I may be a minority but I never liked the Spring Schema configuration. To me it feels a bit like configuration for configuration.

Annotations came along and improved things, with the caveat in that you have to import libraries for all those annotations. I like annotations but  there is a good case for having all your DI information in a central place so you can actually see how your app hangs together. Finally you sometimes need to create managed objects you can't annotate.

Java Spring configuration makes things better with compile time safety, but I had to rethink the way I did a lot of my wiring, as I had to be careful how I did my wiring as I  lost some of the lazy eval that you get in a Spring context as your Java code evaluates immediately when the ApplicationContext starts up.

So, Java based DI is nice but how can we use Java 8.0 to improve it?

Apply that Lambda Hammer

Right so this is the part of the post that starts applying the new hammer in Java 8.0: Lambdas.

Firstly Lambdas give a type safe way of deferring execution till it's needed.

So, lets first create a wrapper object called "ObjectDefinition" who's job it is to define how an object should be created and wired with various values. It works by instantiating the class we want to create and object from (In this case we have a class called "MyObject"). We also give it a list of java.util.function.BiConsumer interfaces which are mapped to a specific value. This list will be used to perform the actual task of setting values on the object.

ObjectDefintion then instantiates the object using normal reflection and then runs though this list of BiConsumer interfaces, passing the the instance of the concrete object and the mapped value.

Assuming we give our ObjectDefinition a fluent DSL we can do the following to define the object by adding the set() method which takes a BiConsumer and the value to set and populates the BiConsumer list as follows:


  MyObject result = new ObjectDefinition()
    .type(MyObject.class)
    .set((myObject, value)-> myObject.setA(value), "hello world")
    .set((myObject, value)-> myObject.setB(value), "hallo welt")
    .create();

The create() method simply instantiates a MyObject instance and then runs through the list of BiConsumers and invokes them passing the mapped value.

Method pointers??!! in Java??!! (Well Kinda)

Now, Another interesting feature in Java 8.0 is Method references, which is a feature where the compiler wraps a method in a functional interface provided that that method can map to the signature of that functional interface.

Method references allow you to map to an arbitrary instance of an object provided that the first parameter of that method is that instance value, and the subsequent parameters match it's parameter list.

This allows us to map a BiConsumer to a setter where the first parameter is the target instance and the second parameter is the value passed to the setter:

  
   MyObject result = new ObjectDefinition()
     .type(MyObject.class)
     .set(MyObject::setA, "hello world")

     .set(MyObject::setB, "hallo welt")
     .create();


Method references provide an interesting feature in that it provides a way of passing a reference to a method in a completely type safe manner. All the examples require the correct types and values to be set and the setter method needs to correspond to that type.

It's Container Time

So now we have  a nice little DSL for building objects, but what about sticking it into a container and allowing our ObjectDefinition to inject references to other values.

Well, assuming we have this container, which conveniently provides a build() method which provides a hook to add new ObjectDefinitions.

We now have a container we can use to inject different objects in that container:

     Container container = create((builder) -> {
          builder
              .define(MyObject.class)
              .set(MyObject::setA, "hello world");
     });
     String myString = container.get(MyObject.class);        



Our Container object has the define() method which creates an instance of an ObjectDefinition, which is then used to define how the object is created.

But what about dependencies?

Dependency Injection is no fun without being able to inject dependencies, but since we have a container we can now reference other objects in the container.

To this end we add the inject() method to our ObjectDefinition type, this can then be used to reference another object in the container by it's type:

   Container container = create((builder) -> {
      builder.define(String.class)
             .args("hello world");

      builder.define(MyObject.class)
             .inject(MyObject::setA,String.class);
   });
   MyObject myString = container.get(MyObject.class);


In this example we map an additional object of type String (the args() method here is method which can map values to the the constructor of an object). We then inject this String calling the inject() method.

Cycle of Life.

We can use the same approach of Lambdas and Method References to manage the life cycle of an object in the container.

Assuming we want to run an initialisation method after all the values have been set, we simply add a new Functional interface which is invoked after all the values are set.

Here we use the a java.util.function.Consumer interface where the parameter is the instance we want to call the initialisation code on.

    Container container = create((builder) -> {
      builder.define(MyObject.class)
             .set(MyObject::setA,"hello world")
             .initWith(MyObject::start);
    });
    MyObject myString = container.get(MyObject.class);



In this example we added a start() method to our MyObject class. This is then passed to the ObjectDefinition as a Consumer via the initWith() method.

Yet Another Dependency Injection Container

So all these techniques (and more) are included in the YADI Container, which stands for Yet Another Dependancy Injection Container.

The code is available on Github at https://github.com/jexenberger/yadi. And is licensed under an Apache License.

2 comments:

kungfupfirsich said...

Where is the promised improvement?

And what do you mean by "Lambdas give a type safe way of deferring execution"? Lambdas are just Syntax.

"I like annotations but there is a good case for having all your DI information in a central place so you can actually see how your app hangs together."
There is tools for that, you know.

julian_za said...

@kungfupfirsich
Because Lambdas are essentially interfaces you have a way of choosing when you wish to invoke them. This is useful for lazy initialization such as often required in a DI container.

I could do this with anonymous inner classes but it would be ugly.

Tools are nice but it's still better to look directly at the code if you can.