DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. Type Safe Dependency Injection Using Java 8.0

Type Safe Dependency Injection Using Java 8.0

Julian Exenberger user avatar by
Julian Exenberger
·
Jun. 30, 14 · Interview
Like (0)
Save
Tweet
Share
9.38K Views

Join the DZone community and get the full member experience.

Join For Free

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();
   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?
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 YetAnother Dependancy Injection Container.

The code is available on Github at https://github.com/jexenberger/yadi. And is licensed under an Apache License.
Dependency injection Java (programming language) Object (computer science) Container Spring Framework

Published at DZone with permission of , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Spring Cloud: How To Deal With Microservice Configuration (Part 1)
  • What Should You Know About Graph Database’s Scalability?
  • Kotlin Is More Fun Than Java And This Is a Big Deal
  • Fraud Detection With Apache Kafka, KSQL, and Apache Flink

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: