Inspired by the latest developments in Java and other open source frameworks like Guice, today I worked for a couple of hours
on creating a small dependency injection framework (on the lines of guice), which I named it as 'Funny Dependency Injection' framework.
This framework has only one custom annotation, which annotates a constructor, to provide dependency injection (only constructor
injection in this example).
Here's the code for the 'Shoot' annotation:
And here's the client class, for which the 'Shoot' annotation is used:
In the above class, you can see the 2 parameters for Client's constructor.
These dependencies will be injected at runtime, with the help of "Shoot" annotation.
The 'Service' and the 'NewService' interfaces are listed below:
And here are 2 implementations of 'Service' interface:
And here's an implementation for 'NewService' interface:
Below are 2 classes, which are part of this funnyDI framework..and which are used for configuration
(dependency mapping information):
And below is the class used for configuration by the user of 'funnyDI' framework, to provide
configuration (dependency mapping information):
And here's the core class of this funny dependency injection framework, which uses java reflection
to find the dependency and inject it:
There's one more class that is part of this funny DI framework, which initializes the configuration
(based on the configuration module used) and returns the 'Shooter' class, which further provides the dependency injection:
And here's the main java class, which acts as a entry point for this funny application, which uses
'Funny Dependency Injection':
Thats it! When I ran the above program, "I'm doing something in ServiceImpl2" is printed, followed by
"I'm doing something new", in the next line.
You can find the source code for this
funny DI framework on funnydi.
If you have any funny comments, please don't hesitate to post! ;)
DISCLAIMER: The code posted above was created for fun and to learn something new.
The above framework needs to be improvised a lot, if you want to implement it, in your own project. So, don't use it blindly.
The views expressed on this blog are my personal views and do not reflect the views of
my employer or campaigns I am supporting.
All sample code is provided for illustrative purposes only. These examples have not been thoroughly tested under all conditions. The writer therefore, cannot guarantee or imply reliability, serviceability, or function of these programs.
All programs contained herein are provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.