imgn inject API GitHub

Builder Overrides

The problem

The graph that ServiceLoader discovers is the production graph. A test — or a main method wiring a simulation — often needs that exact graph with a few bindings replaced: the real gateway swapped for a recording fake, a clock pinned to a fixed instant. Editing the beans to make them swappable would pollute production code for the test's benefit.

How it solves it

Injector.builder() creates an injector from the same discovered factories, with explicit bindings that shadow any discovered binding for the same key. Overrides win silently — no duplicate check — because replacing is their purpose:

Injector injector = Injector.builder()
        .bind(Clock.class, Clock.fixed(instant, ZoneOffset.UTC))
        .bind(Key.of(String.class, Names.named("greeting")), "Hi")
        .bindProvider(Gateway.class, RecordingGateway::new)
        .build();

Everything downstream sees the override: any bean depending on Clock receives the fixed one, with the rest of the graph untouched. That includes resolutions through a child injector, which never rebuilds the discovered bean an override replaced.

A binding does not need a discovered binding to replace: it also supplies a dependency nothing else binds, such as a configuration record built in main. A type that neither has an @Inject constructor nor an accessible no-argument constructor gets no generated factory, so a binding is how it enters the graph:

Injector injector = Injector.builder()
        .bind(DisplayConfig.class, new DisplayConfig(1920, 1080))
        .build();

build() checks that every bean's dependencies are bound, overrides included, and throws one UnsatisfiedDependencyException listing every missing one.

The same pair of operations exists on childBuilder(); the difference is lifecycle. Builder overrides bake replacement into a standalone injector at creation; a child layers bindings over a live parent.

Limitations