Skip to main content

Transient bindings

By default every instance obtained using ActiveJ Inject is singleton. This means that instances are cached when retrieved the first time and then reused on future Injector#getInstance calls. This behavior is different from a default behaviour of a majority of other dependency injection frameworks.

However, there are situations when you do not want to cache an instance, but rather you want to create a new instance each time. For that you can use "transient" binding. Such bindings are special because instances retrieved using "transient" bindings are not cached. Such instances are recreated each time when being retrieved.

note

Transient bindings are not transitive. If you have a non-transient binding A that depends on an instance provided via a transient binding B, a binding A is not itself transient. It will use a cached instance of a transient binding.

Defining transient bindings

There are multiple ways to define a transient binding.

We can use asTransient() method from the ModuleBuilder DSL and mark a binding as transient like this:

bind(double.class).to(Math::random).asTransient();

Or, alternatively we can use @Transient annotation to annotate methods already annotated with @Provides annotation:

@Providesdouble random() {    return Math.random();}

When you retrieve an instance of double from the injector you will get a new random number each time.

Transient binding example

Let's look at another example. Imagine that our application needs to know a current time. Therefore, we cannot cache an instance of an Instant. So, we should create a binding for an Instant as transient.

Let's define a module that defines a binding for an instance of current Instant (notice the @Transient annotation):

static class CurrentTimeModule extends AbstractModule {  @Provides  @Transient  Instant currentInstant() {    return Instant.now();  }}

Now let's retrieve two instances of an Instant from the injector waiting for a second between each retrieval:

Injector injector = Injector.of(new CurrentTimeModule());
System.out.println(injector.getInstance(Instant.class));Thread.sleep(1000);System.out.println(injector.getInstance(Instant.class));

If we run the example we will see that retrieved instances of Instant differ by approximately 1 second.

You can find a full example on Github