Type Safe Dependency Injection Using Java 8.0
Join the DZone community and get the full member experience.
Join For FreeSo 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)
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(); String myString = container.get(MyObject.class);
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");
});
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?
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);
Cycle of Life.
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);
Yet Another Dependency Injection Container
The code is available on Github at https://github.com/jexenberger/yadi. And is licensed under an Apache License.
Published at DZone with permission of , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments