ActiveJ Inject Basics
- ActiveJ Inject :: Basics
- ActiveJ Inject :: Internals
ActiveJ Inject :: Basics
Dependency Injection, Keys, Bindings
- Applications consist of components and each component has an inner id called Key.
- Key consists of the Type type and nullable qualifier Object (useful when you need different implementations of the same Type):
- Application components can require some dependencies in order to be created.
- Dependency Injection takes care of supplying application components with these required objects.
- In order to do it, we need to specify what it needs to provide and how to use the provided objects.
- Therefore, Binding has two corresponding attributes:
Binding is like a “recipe” of how to create an instance of a component:
- dependencies show what ingredients should be used
- compiler knows how to cook them together
- Now we need something that can use the recipe to cook the component properly, and here comes Injector.
- Provides all the required dependencies (injects) for the component recursively traversing the dependencies graph in a postorder way and creates them first.
- Bindings are by default singletons - if an instance was created once, it won’t be recreated from scratch again. If it is needed for other bindings, Injector will take it from cache. You don’t need to apply any additional annotations for it.
- To provide the requested key, Injector recursively creates all of its dependencies and falls back to injector of its parent scope if binding in its scope is not found.
ActiveJ Inject :: Internals
In short - Scope gives us “local singletons” which live as long as the scope itself. ActiveJ Inject scopes are a bit different from other DI libraries:
- The internal structure of the Injector is a prefix tree and the prefix is a scope.
- The identifiers (or prefixes) of the tree are simple annotations.
enter the scope. This means you create an Injector and its scope will be set to the one that it’s entering.
- This can be done multiple times, so you can have N injectors in certain scope.
This example can show you how scopes works.
Dependency graph is hard to create directly, so we provide automatic graph transformation, generation and validation mechanisms with a simple yet powerful DSL.
All of these preprocessing steps are performed in start-up time by compiling Modules:
- Each module exports bindings which are combined with each other. If there are two or more bindings for any single key,
they are reduced into one binding with user-provided Multibinder reduce function:
- This simple solution makes it trivial to implement multibinder sets/maps or any app-specific multibinder
- If no Multibinder is defined for particular key, exception is thrown
- If dependency graph has missing dependencies, they are automatically generated with BindingGenerator:
- BindingGenerators are user-defined and exported by Modules
- There is an implicit DefaultModule with default BindingGenerator, which automatically provides required dependencies by scanning @Inject annotations of required classes
- User-specified modules can also export custom binding generators for special classes
- You can opt-out of using DefaultModule and its default BindingGenerators
- All bindings are transformed with user-provided BindingTransformers:
- To intercept/modify/wrap provided instances
- To intercept/modify/wrap the dependencies of provided instances
- Multibinders, BindingGenerators and BindingTransformers can be made with clean and extremely simple Java8+ functional DSL
- Resulting dependency graph is validated - checked for cyclic and missing dependencies, then compiled into a final scope tree and passed to Injector
It’s trivial to manually implement the Module interface, but it’s even easier to extend AbstractModule, which supports @Provides method scanning and the DSL for creating/transforming/generating bindings.
We’ve compared ActiveJ Inject to Guice and Spring in the same scenario, using JMH as the benchmark tool. We ran benchmarks in AverageTime mode and made 20 measurements. All measurement results are represented in nanoseconds.
Benchmarks were launched on a machine with the following parameters: Ubuntu 18.04 bionic, Kernel: x86_64 Linux 4.15.0-55-generic, CPU: Intel Core i5-8400 @ 6x 4GHz [27.8°C].
You can find benchmark sources on GitHub.
To represent the main concepts and features of ActiveJ Inject, we’ve created an example that starts with low-level DI concepts and gradually covers more specific advanced features.
$ git clone https://github.com/activej/activej
And import it as a Maven project. Check out tag v4.1. Before running the examples, build the project.
This example is located at activej -> core-inject -> test and named DiFollowUpTest
In this example we have a kitchen, where you can automatically create tasty cookies with wonderful ActiveJ Inject. Before we get to cooking, note that there are several POJOs with default constructors marked with @Inject annotation: Kitchen, Sugar, Butter, Flour, Pastry and Cookie.
Let’s bake a Cookie using ActiveJ Inject in a hardcore way. First of all, we need to provide all the ingredients for the cookie: Sugar, Butter and Flour. Next, there is a recipe for Pastry, which includes ingredients (Sugar, Butter and Flour) we already know how to get. Finally, we can add a recipe of how to bake a Cookie.
It’s baking time now! Just create the Injector with all these recipes and ask it for your Cookie instance.
Bind Using ModuleBuilder
This time we will bake a Cookie with a simple DSL. We will bundle our recipes for Sugar, Butter and Flour in a ‘cookbook’ module.
Instead of creating bindings explicitly and storing them directly in a map, we just bind the recipes in our module and then give it to the injector.
It’s time for real Cookie business. Instead of making bindings explicitly, we will use the declarative DSL.
Like in the previous example, we create a cookbook module, but this time all bindings for the ingredients will be created
automatically from the provider methods. These methods are marked with the
Bind Using Instance or Class Scan
Sometimes it happens that you prepare an injection scheme, but this scheme is not a module. But there is a scan() method which can help you to make a connection between DI entities and your scheme.
If your class provides a scheme, you can use it easily:
Automatic Bind Using
When we created our POJOs, we’ve marked their constructors with
If a binding depends on a class that has no known binding, injector will try to automatically generate binding for it.
It will search for
@Inject annotation on its constructors, static factory methods or the class itself (in this case
the default constructor is used) and use them as a factory in generated binding.
Since nothing depends on the Cookie binding, by default no bindings will be generated at all. Here we use a plain bind to tell the injector that we want this binding to be present. Thus the whole tree of bindings it depends on will be generated:
Let’s be trendy and bake a sugar-free cookie. In order to do so, along with
@Provides annotation, we will
also use @Named annotation and provide two different Sugar, Pastry and Cookie factory functions. This
approach allows using different instances of the same class. Now we can tell our injector, which of the
cookies we need - a usual one or sugar-free.
You can also use ModuleBuilder:
Non-singleton Instances Using Scopes
Our cookies turned out to be so tasty, that a lot of people want to try them. However, there is a problem, ActiveJ Inject makes instances singleton by default. Yet, we can’t sell the same one cookie to all our customers.
Luckily, there is a solution: we can use a custom @ScopeAnnotation
@OrderScope to create
So our cookbook will look as follows:
In this way, only kitchen will remain singleton:
We received 10 orders from our customers, so now we need 10 instances of cookies:
- First, we inject an instance of Kitchen. Now this instance is stored in the root scope injector.
- Next, we create 10 subinjectors which enter
- Each subinjector creates only one instance of Cookie and refers to the single Kitchen instance of their parent root scope.
You can configure the process of how your injector gets instances and transform this process. For example, you can simply add some logging by overriding configure method:
Now you will receive an output which will represent the time when an instance was created and the instance itself.