What is ActiveInject?

ActiveInject is a lightning-fast and powerful dependency injection library. It has a lot of tools and features to offer: support for nested scopes, singletons and transient bindings, modules, multi-threaded, and single-threaded injectors.

At the same time, it’s thoroughly optimized with all the dependencies graph preprocessing performed at startup time. According to the benchmarks, in some scenarios, ActiveInject is 5.5 times faster than Guice and hundreds of times faster than Spring DI. You can check the benchmark sources here.

ActiveInject_ is an independent technology of ActiveJ platform. It has no third-party dependencies on its own and can be used as a stand-alone DI library._

Getting Started

Let’s try the library out and bake some virtual cookies using ActiveInject. A cookie requires the following ingredients: FlourSugar and Butter. These ingredients form a Pastry which can be baked into a Cookie. Assume each of these entities has a POJO. Let’s start with a basic example:

public void provideAnnotation() {
  Module cookbook = new AbstractModule() {
     @Provides
     Sugar sugar() { return new Sugar("WhiteSugar", 10.f); }

     @Provides
     Butter butter() { return new Butter("PerfectButter", 20.0f); }

     @Provides
     Flour flour() { return new Flour("GoodFlour", 100.0f); }

     @Provides
     Pastry pastry(Sugar sugar, Butter butter, Flour flour) {
        return new Pastry(sugar, butter, flour);
     }

     @Provides
     Cookie cookie(Pastry pastry) {
        return new Cookie(pastry);
     }
  };

  Injector injector = Injector.of(cookbook);
  injector.getInstance(Cookie.class).getPastry().getButter().getName());
}

Here we’ve created an AbstractModule named cookbook that contains all the required bindings, or “recipes”, for the ingredients. Call Injector.getInstance method to get an instance of the Cookie.

How does it work from the inside? Injector provides all the required dependencies for the component recursively traversing the dependencies graph in a postorder way. So it first created SugarButter and Flour, the next was Pastry, and finally a Cookie.

#java #dependency injection #java library #dependency injection tutorial

ActiveInject. Fast and Lightweight Dependency Injection Library
1.80 GEEK