ConfigurableApplicationContext class abstract interface

An application context that can also be set up, started, paused and closed.

ApplicationContext is what code that uses the beans needs. This interface is for the code that owns the context: main, a test, or Spring Boot's SpringApplication, which returns one from run. Before refresh it accepts more modules, post-processors and listeners; refresh creates the beans; close stops and destroys them. A bean that must shut the application down can inject it.

// A plugin module and a post-processor join before the start; the
// finally block destroys the beans even when the app fails.
final context = AnnotationConfigApplicationContext([appBeans])
  ..register(pluginBeans)
  ..addBeanFactoryPostProcessor(MyPostProcessor())
  ..refresh();
try {
  context.getBean<App>().run();
} finally {
  context.close();
}

Spring (Java):

try (var context = new AnnotationConfigApplicationContext()) {
  context.register(AppConfig.class, PluginConfig.class);
  context.addBeanFactoryPostProcessor(new MyPostProcessor());
  context.refresh();
  context.getBean(App.class).run();
}
Implemented types

Properties

applicationListeners → List<GenericApplicationListener>
The listener objects the context holds, for diagnostics.
no setter
autowireCapableBeanFactory → AutowireCapableBeanFactory
The factory that injects objects the container did not create, such as a @Configurable Flutter State (autowireBean).
no setterinherited
beanDefinitionCount → int
How many definitions are registered here (objects added with registerSingleton are not counted).
no setterinherited
beanDefinitionNames → List<String>
The names of the definitions registered here, in registration order. Objects added with registerSingleton are not definitions and are not listed.
no setterinherited
beanFactory → ConfigurableListableBeanFactory
The bean factory inside the context, which holds the bean definitions and the created beans.
no setter
displayName → String
The name used in error messages and toString: the id, or the class name with the id when one was given explicitly.
no setterinherited
environment → ConfigurableEnvironment
The configuration the context was built with: properties from all sources, the active profiles and the type conversion used for them.
no setteroverride
hashCode → int
The hash code for this object.
no setterinherited
id → String
A name that tells this context apart from others in logs, for example a parent and a child.
no setterinherited
isActive → bool
Whether beans can be looked up: true from the start of refresh until close has finished, false again after a failed refresh.
no setter
isClosed → bool
Whether close (or closeAsync) has completed; a closed context cannot be started again.
no setter
isRunning → bool
Whether the background work is running; the context asks before starting or stopping the bean.
no setterinherited
parent ↔ ApplicationContext?
The context this one extends, or null.
getter/setter pairoverride-getter
parentBeanFactory → BeanFactory?
The factory consulted when a lookup finds nothing here; null for a root factory.
no setterinherited
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited
startupDate → DateTime?
When the refresh started, for uptime reports; null before.
no setterinherited

Methods

addApplicationListener(GenericApplicationListener listener) → void
Adds a listener object that is not a bean; works before and after refresh.
addBeanFactoryPostProcessor(BeanFactoryPostProcessor processor) → void
Adds a post-processor that refresh runs once every bean definition is loaded and before any bean is created.
addListener<E>(void listener(E event), {int order}) → ListenerRegistration
Calls listener for every event published from now on whose type, or payload type, is E.
inherited
addProtocolResolver(ProtocolResolver resolver) → void
Teaches getResource a custom location prefix, such as asset: for Flutter assets.
close() → void
Shuts the context down: publishes ContextClosedEvent, stops the running Lifecycle beans and destroys the singletons (each bean after the beans that depend on it), which runs their @PreDestroy and destroy methods.
closeAsync() → Future<void>
Like close, but waits for asynchronous shutdown work and completes once the context is closed.
containsBean(String name) → bool
Whether a bean or alias named name exists here or in a parent (&name only for a factory bean). Creates nothing.
inherited
containsBeanDefinition(String name) → bool
Whether a definition is registered here under exactly name. Aliases, parent beans and objects added with registerSingleton do not count.
inherited
containsBeanOfType(Type type, {String? qualifier, bool includeAncestors = true}) → bool
Whether injecting type would find a bean, without creating any.
inherited
containsLocalBean(String name) → bool
Whether this factory itself, ignoring the parent, has a bean or alias named name (&name only for a factory bean).
inherited
findAnnotationOnBean<A extends Object>(String beanName) → A?
The first annotation of type A on the class (or @Bean method) of the bean named beanName, or null. Creates no bean. Looks in the parent when the bean is not known here, and throws NoSuchBeanDefinitionException when no factory has it. Spring: findAnnotationOnBean.
inherited
findBean<T extends Object>({String? qualifier}) → T?
Like getBean, but returns null when no bean matches, for a collaborator the caller can do without. Still throws NoUniqueBeanDefinitionException when several match and none wins. Spring: getBeanProvider(T).getIfAvailable().
inherited
getAliases(String name) → List<String>
The other names of the bean named name: its aliases, plus its bean name when name is itself an alias. Empty when there are none or no bean has that name.
inherited
getBean<T extends Object>({String? qualifier}) → T
The bean of type T, created if it does not exist yet. With qualifier, only the bean with that name, alias or @Qualifier value.
inherited
getBeanByName(String name) → Object
The bean registered under name or one of its aliases, created if needed; looks in the parent when the name is not known here.
inherited
getBeanNamesForAnnotation<A extends Object>() → List<String>
The names of this factory's definitions whose class (for a @Bean method: the method or the returned class) carries an annotation of type A or of a subclass of A, so asking for Component also finds @Service beans. Creates no bean. Spring: getBeanNamesForAnnotation.
inherited
getBeanNamesForType(Type type, {bool includeNonSingletons = true}) → List<String>
The names of this factory's beans that can be used as type, in registration order: definitions first, then objects added with registerSingleton. Creates no bean.
inherited
getBeanProvider<T extends Object>({String? qualifier}) → ObjectProvider<T>
A handle on the beans of T that creates nothing until it is used.
inherited
getBeansOfType<T extends Object>({bool includeNonSingletons = true}) → Map<String, T>
This factory's beans of T by name, in the order of getBeanNamesForType; creates those that do not exist yet. A bean whose @Bean method returned null is left out.
inherited
getBeansWithAnnotation<A extends Object>() → Map<String, Object>
The beans named by getBeanNamesForAnnotation, by name; creates them. Spring: getBeansWithAnnotation.
inherited
getMessage(String code, {List<Object?> args = const [], String? defaultMessage, String? locale}) → String
The text for code in locale, with args filled into its {0}, {1}, ... placeholders.
inherited
getMessageFromResolvable(MessageSourceResolvable resolvable, {String? locale}) → String
The text for the first code of resolvable found in locale, with its arguments filled in; else its default message; else a NoSuchMessageException. Use it to show validation errors and other messages described by codes.
inherited
getResource(String location) → Resource
The resource at location. Nothing is read yet, and the resource may not exist: check Resource.exists before reading when it may be missing. Never returns null; an unknown prefix gives a resource that does not exist.
inherited
getResources(String locationPattern) → List<Resource>
All resources matching locationPattern, possibly none. A location without wildcards gives that one resource when it exists.
inherited
getSortedBeans<T extends Object>({String? qualifier}) → List<T>
Every bean of T here and in the parent factories, sorted to be used in order: PriorityOrdered beans first, then by Ordered.order, @Order or jakarta @Priority (lower first), then by registration.
inherited
getType(String name) → Type?
The type of the bean named name, without creating it: the declared class (or what a SmartInstantiationAwareBeanPostProcessor predicts), the product type for a factory bean (&name: the factory's class), the runtime type of an object added with registerSingleton. null when no bean has that name.
inherited
isPrototype(String name) → bool
Whether every lookup of the bean named name creates a new instance. For a FactoryBean, whether its product is created per lookup (this creates the factory); &name asks about the factory itself. A bean in a custom scope is neither a singleton nor a prototype. Throws NoSuchBeanDefinitionException for an unknown name.
inherited
isSingleton(String name) → bool
Whether the bean named name is one shared instance. For a FactoryBean, whether its product is shared (this creates the factory); &name asks about the factory itself. Throws NoSuchBeanDefinitionException for an unknown name.
inherited
isTypeMatch(String name, Type type) → bool
Whether the bean named name can be used as a type, judged from the types its definition declares, without creating it.
inherited
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
pause() → void
Stops the running Lifecycle beans for a while, keeping every bean alive, then publishes ContextPausedEvent; restart resumes them.
pauseAsync() → Future<void>
Like pause, but waits for the SmartLifecycle.stopWithCallback callbacks of each phase (at most the lifecycle processor's timeout per phase) before ContextPausedEvent is published.
publishEvent<T extends Object>(T event) → void
Delivers event to every listener that accepts it. By default the listeners run before this call returns, and a listener error reaches the caller; with an asynchronous multicaster they run later. An event that is not an ApplicationEvent is wrapped in a PayloadApplicationEvent<T>.
inherited
refresh() → void
Starts the context: registers the beans, checks them and creates every singleton that is not lazy. Call it once.
refreshAsync() → Future<void>
Like refresh, for beans whose init callbacks are asynchronous.
register(Object component) → void
Adds beans before refresh: a BeanModule, or an object that registers beans in code (a BeanRegistrar, an ImportSelector or an ImportBeanDefinitionRegistrar).
registerShutdownHook() → void
Closes the context when the process is asked to stop (Ctrl+C or a kill), so that the beans release their resources.
removeApplicationListener(GenericApplicationListener listener) → void
Removes a listener added with addApplicationListener; it receives no more events.
restart() → void
Brings the lifecycle beans back to the state right after refresh, typically after pause, then publishes ContextRestartedEvent.
start() → void
Starts the background work. The context does not call it when isRunning is already true; an error thrown here fails the start as an ApplicationContextException.
inherited
stop() → void
Stops the background work. The context calls it only when isRunning is true; an error thrown here is logged and the other beans are still stopped.
inherited
toString() → String
A string representation of this object.
inherited

Operators

operator ==(Object other) → bool
The equality operator.
inherited