A place that keeps bean instances for a span of your choosing, such as a screen, a session or a job, and so defines a custom bean scope.
Singletons live as long as the container and prototypes not at all.
When beans should live exactly as long as something else, implement a
scope, register it with ConfigurableBeanFactory.registerScope and
declare the beans with @Scope('name'). The container calls get on
every lookup of such a bean and hands over its destroy callbacks through
registerDestructionCallback; the scope runs them when it ends.
SimpleMapScope is a ready-made one. Spring calls this interface
Scope; here that name is the annotation.
// A scope that keeps one instance per name until removed.
class ZoneScope implements CustomScope {
final _objects = <String, Object>{};
@override
Object get(String name, Object Function() objectFactory) =>
_objects[name] ??= objectFactory();
@override
Object? remove(String name) => _objects.remove(name);
@override
void registerDestructionCallback(String name, void Function() cb) {}
@override
String? get conversationId => null;
}
factory.registerScope('zone', ZoneScope());
@Service()
@Scope('zone')
class RequestState {}
Spring (Java):
class ZoneScope implements Scope {
private final Map<String, Object> objects = new HashMap<>();
public Object get(String name, ObjectFactory<?> factory) {
return objects.computeIfAbsent(name, n -> factory.getObject());
}
public Object remove(String name) { return objects.remove(name); }
public void registerDestructionCallback(String name, Runnable cb) {}
public Object resolveContextualObject(String key) { return null; }
public String getConversationId() { return null; }
}
beanFactory.registerScope("zone", new ZoneScope());
Properties
- conversationId → String?
-
An id of the current span (a session id, say), or
null.no setter - hashCode → int
-
The hash code for this object.
no setterinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
get(
String name, Object objectFactory()) → Object -
The instance of the bean
namein the current span, created withobjectFactorywhen the scope does not hold one yet. Throw aStateErrorwhen the scope is not active right now (no screen open): the container reports it as aScopeNotActiveException. -
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
registerDestructionCallback(
String name, void callback()) → void -
Keeps
callback, which runs the destroy callbacks of the instance of the beanname; the scope calls it when it destroys that instance. -
remove(
String name) → Object? -
Removes and returns the instance of the bean
name, ornull. Its destruction callback must not run: the caller owns the object now (destroyScopedBeanremoves it and then destroys it). -
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited