Scopes
The problem
Some objects are cheap and stateless — a fresh one per use is correct and avoids shared-state bugs. Others are expensive or must be shared — a connection pool, a registry. One instantiation policy cannot fit both, and hand-managing "the shared ones" reintroduces the global variables injection was meant to remove.
How it solves it
The default is prototype: every resolution builds a new instance. Sharing is opt-in, declared where the bean is declared.
@Singleton is built in — one instance per injector, created on first use
(or when the injector is created, for an eager one),
exactly once even under concurrent resolution:
@Singleton
public final class Registry {
@Inject
public Registry() {}
}
Injector injector = Injector.create();
assert injector.getInstance(Registry.class) == injector.getInstance(Registry.class);
@Provides methods scope the same way — put @Singleton on the method.
Inherited scopes
A bean class that declares no scope inherits the one its supertypes declare, through the superclass chain and every superinterface, at any depth. A framework can then scope every implementation of one of its interfaces:
@ViewScoped
public interface View {}
public final class Editor implements View { // @ViewScoped
@Inject
public Editor() {}
}
Along each path, the nearest declaration wins: an interface that declares its
own scope hides the scopes of the interfaces it extends. A scope declared on
the bean itself always wins. Different scopes inherited along different paths
are a compile error, which asks to declare one on the bean. Supertypes compiled
elsewhere count too: the processor reads their scope from the class file, so
the scoping annotation needs CLASS or RUNTIME retention.
Custom scopes
A scope is a pair: an annotation meta-annotated with @ScopingAnnotation, and
a Scope implementation that wraps the bean's provider with a caching policy.
Implementations are discovered through ServiceLoader.
@ScopingAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface ThreadScoped {}
public final class ThreadScope implements Scope {
@Override
public Class<? extends Annotation> annotationType() {
return ThreadScoped.class;
}
@Override
public <T> Provider<T> wrap(Provider<T> provider) {
return new ThreadScopedProvider<>(provider); // caches per thread
}
}
@ThreadScoped
public final class RequestScopedToken {
@Inject
public RequestScopedToken() {}
}
The wrap-a-provider contract keeps custom scopes small: the framework hands the scope the raw building provider once, at registry construction, and every resolution goes through the returned wrapper.
Limitations
- Scopes control instantiation. Releasing scoped instances is a separate
concern, handled by lifecycle callbacks: a
@PreDestroymethod runs when the owning injector closes. - A bean carries at most one scoping annotation.
- A
@Providesmethod's scope is never inherited from its return type: only the method's own annotation counts. - A scoping annotation has exactly one
Scope: two discovered implementations for the same annotation are an error at injector creation (ScopeResolutionException), so a jar cannot silently replace a scope, built-in@Singletonincluded. - Scopes are declared on the bean, not chosen at the injection point; a
consumer cannot request "a fresh instance" of a singleton (though injecting a
Providerof a prototype bean gives fresh instances on demand). - A scoping annotation with no
Scopeservice is child-local: the child injectors that host it cache its instances, and resolving such a bean elsewhere fails. Other scoped beans anchor to the injector whose registry declared them.