AnnotationConfigApplicationContext class
The application context of this package: it builds its beans from the
BeanModules the generator writes for @ComponentScan.
It is the only implementation of ConfigurableApplicationContext here;
ApplicationContext.run and Spring Boot's SpringApplication create
one for you. Construct it yourself when something must happen between
creating the context and starting it: register more modules,
registerBean a bean in code, add a post-processor, set a parent. Then
call refresh. A subclass can override the template methods
postProcessBeanFactory, onRefresh and onClose.
Some of its own parts can be replaced by declaring a bean with a
well-known name: messageSourceBeanName for the translated messages,
applicationEventMulticasterBeanName for event delivery,
lifecycleProcessorBeanName for starting and stopping lifecycle
beans, conversionServiceBeanName for @Value conversion.
@ComponentScan()
final BeanModule appBeans = $appBeans;
// The `dev` profile is set before any bean definition is loaded.
void main() {
final context = AnnotationConfigApplicationContext(
[appBeans],
environment: StandardEnvironment()..setActiveProfiles(['dev']),
)..refresh();
context.getBean<App>().run();
context.close();
}
Spring (Java):
var context = new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles("dev");
context.register(AppConfig.class);
context.refresh();
context.getBean(App.class).run();
context.close();
- Implemented types
Constructors
-
AnnotationConfigApplicationContext(List<
BeanModule> modules, {ApplicationContext? parent, ConfigurableEnvironment? environment, ResourceLoader? resourceLoader, String? id}) -
Creates a context for
modules; nothing is loaded or created until refresh.
Properties
-
applicationListeners
→ List<
GenericApplicationListener> -
The listener objects the context holds, for diagnostics.
no setteroverride
- autowireCapableBeanFactory → AutowireCapableBeanFactory
-
The factory that injects objects the container did not create, such
as a
@ConfigurableFlutterState(autowireBean).no setteroverride - beanDefinitionCount → int
-
How many definitions are registered here (objects added with
registerSingletonare not counted).no setteroverride -
beanDefinitionNames
→ List<
String> -
The names of the definitions registered here, in registration order.
Objects added with
registerSingletonare not definitions and are not listed.no setteroverride - beanFactory → ConfigurableListableBeanFactory
-
The bean factory inside the context, which holds the bean
definitions and the created beans.
no setteroverride
-
conditionEvaluations
→ List<
ConditionEvaluation> -
Every condition the refresh evaluated, with its outcome, in
evaluation order.
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 setteroverride - environment → ConfigurableEnvironment
-
The configuration the context was built with: properties from all
sources, the active profiles and the type conversion used for them.
final
- 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.
latefinal
- introspector → BeanIntrospector
-
The generated descriptions of the
@Introspectedclasses of this context's modules: their properties and methods, which data binding, validation and SpEL use instead of reflection. Classes it does not know are looked up in BeanIntrospector.shared.final - isActive → bool
-
Whether beans can be looked up:
truefrom the start of refresh until close has finished,falseagain after a failed refresh.no setteroverride - isClosed → bool
-
Whether close (or closeAsync) has completed; a closed context
cannot be started again.
no setteroverride
- isRunning → bool
-
Whether the background work is running; the context asks before
starting or stopping the bean.
no setteroverride
- parent ↔ ApplicationContext?
-
The context this one extends, or
null.getter/setter pairoverride - parentBeanFactory → BeanFactory?
-
The factory consulted when a lookup finds nothing here;
nullfor a root factory.no setteroverride - runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- startupDate ↔ DateTime?
-
When refresh started;
nullbefore. Set by the context.getter/setter pairoverride-getter
Methods
-
addApplicationListener(
GenericApplicationListener listener) → void -
Adds a listener object that is not a bean; works before and after
refresh.
override
-
addBeanFactoryPostProcessor(
BeanFactoryPostProcessor processor) → void -
Adds a post-processor that refresh runs once every bean definition
is loaded and before any bean is created.
override
-
addListener<
E> (void listener(E event), {int order = Ordered.lowestPrecedence}) → ListenerRegistration -
Calls
listenerfor every event published from now on whose type, or payload type, isE.override -
addProtocolResolver(
ProtocolResolver resolver) → void -
Teaches getResource a custom location prefix, such as
asset:for Flutter assets.override -
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@PreDestroyand destroy methods.override -
closeAsync(
) → Future< void> -
Like close, but waits for asynchronous shutdown work and completes
once the context is closed.
override
-
containsBean(
String name) → bool -
Whether a bean or alias named
nameexists here or in a parent (&nameonly for a factory bean). Creates nothing.override -
containsBeanDefinition(
String name) → bool -
Whether a definition is registered here under exactly
name. Aliases, parent beans and objects added withregisterSingletondo not count.override -
containsBeanOfType(
Type type, {String? qualifier, bool includeAncestors = true}) → bool -
Whether injecting
typewould find a bean, without creating any.override -
containsLocalBean(
String name) → bool -
Whether this factory itself, ignoring the parent, has a bean or alias
named
name(&nameonly for a factory bean).override -
findAnnotationOnBean<
A extends Object> (String beanName) → A? -
The first annotation of type
Aon the class (or@Beanmethod) of the bean namedbeanName, ornull. Creates no bean. Looks in the parent when the bean is not known here, and throwsNoSuchBeanDefinitionExceptionwhen no factory has it. Spring:findAnnotationOnBean.override -
findBean<
T extends Object> ({String? qualifier}) → T? -
Like getBean, but returns
nullwhen no bean matches, for a collaborator the caller can do without. Still throwsNoUniqueBeanDefinitionExceptionwhen several match and none wins. Spring:getBeanProvider(T).getIfAvailable().override -
getAliases(
String name) → List< String> -
The other names of the bean named
name: its aliases, plus its bean name whennameis itself an alias. Empty when there are none or no bean has that name.override -
getBean<
T extends Object> ({String? qualifier}) → T -
The bean of type
T, created if it does not exist yet. Withqualifier, only the bean with that name, alias or@Qualifiervalue.override -
getBeanByName(
String name) → Object -
The bean registered under
nameor one of its aliases, created if needed; looks in the parent when the name is not known here.override -
getBeanNamesForAnnotation<
A extends Object> () → List< String> -
The names of this factory's definitions whose class (for a
@Beanmethod: the method or the returned class) carries an annotation of typeAor of a subclass ofA, so asking forComponentalso finds@Servicebeans. Creates no bean. Spring:getBeanNamesForAnnotation.override -
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 withregisterSingleton. Creates no bean.override -
getBeanProvider<
T extends Object> ({String? qualifier}) → ObjectProvider< T> -
A handle on the beans of
Tthat creates nothing until it is used.override -
getBeansOfType<
T extends Object> ({bool includeNonSingletons = true}) → Map< String, T> -
This factory's beans of
Tby name, in the order of getBeanNamesForType; creates those that do not exist yet. A bean whose@Beanmethod returnednullis left out.override -
getBeansWithAnnotation<
A extends Object> () → Map< String, Object> -
The beans named by getBeanNamesForAnnotation, by name; creates them.
Spring:
getBeansWithAnnotation.override -
getMessage(
String code, {List< Object?> args = const [], String? defaultMessage, String? locale}) → String -
Looks up the message
codein the context's message source (themessageSourcebean, else the parent's) and fills inargs.override -
getMessageFromResolvable(
MessageSourceResolvable resolvable, {String? locale}) → String -
The text for the first code of
resolvablefound inlocale, with its arguments filled in; else its default message; else a NoSuchMessageException. Use it to show validation errors and other messages described by codes.override -
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 returnsnull; an unknown prefix gives a resource that does not exist.override -
getResources(
String locationPattern) → List< Resource> -
All resources matching
locationPattern, possibly none. A location without wildcards gives that one resource when it exists.override -
getSortedBeans<
T extends Object> ({String? qualifier}) → List< T> -
Every bean of
There and in the parent factories, sorted to be used in order:PriorityOrderedbeans first, then byOrdered.order,@Orderor jakarta@Priority(lower first), then by registration.override -
getType(
String name) → Type? -
The type of the bean named
name, without creating it: the declared class (or what aSmartInstantiationAwareBeanPostProcessorpredicts), the product type for a factory bean (&name: the factory's class), the runtime type of an object added withregisterSingleton.nullwhen no bean has that name.override -
isPrototype(
String name) → bool -
Whether every lookup of the bean named
namecreates a new instance. For aFactoryBean, whether its product is created per lookup (this creates the factory);&nameasks about the factory itself. A bean in a custom scope is neither a singleton nor a prototype. ThrowsNoSuchBeanDefinitionExceptionfor an unknown name.override -
isSingleton(
String name) → bool -
Whether the bean named
nameis one shared instance. For aFactoryBean, whether its product is shared (this creates the factory);&nameasks about the factory itself. ThrowsNoSuchBeanDefinitionExceptionfor an unknown name.override -
isTypeMatch(
String name, Type type) → bool -
Whether the bean named
namecan be used as atype, judged from the types its definition declares, without creating it.override -
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
onClose(
) → void - A hook for subclasses, called last by close and closeAsync, after the singletons are destroyed and before the context counts as closed.
-
onRefresh(
) → void - A hook for subclasses, called by refresh once the message source and the event multicaster exist, before the listeners are registered and the eager singletons are created.
-
pause(
) → void -
Stops the running Lifecycle beans for a while, keeping every bean
alive, then publishes
ContextPausedEvent; restart resumes them.override -
pauseAsync(
) → Future< void> -
Like pause, but waits for the
SmartLifecycle.stopWithCallbackcallbacks of each phase (at most the lifecycle processor's timeout per phase) beforeContextPausedEventis published.override -
postProcessBeanFactory(
ConfigurableListableBeanFactory beanFactory) → void - A hook for subclasses, called by refresh once every bean definition is registered and before the bean factory post-processors run; no bean exists yet.
-
publishEvent<
T extends Object> (T event) → void -
Delivers
eventto this context's listeners, then publishes it in the parent context.override -
refresh(
) → void -
Starts the context: registers the beans, checks them and creates
every singleton that is not lazy. Call it once.
override
-
refreshAsync(
) → Future< void> -
Like refresh, for beans whose init callbacks are asynchronous.
override
-
register(
Object component) → void -
Adds beans before refresh: a BeanModule, or an object that
registers beans in code (a
BeanRegistrar, anImportSelectoror anImportBeanDefinitionRegistrar).override -
registerBean<
T extends Object> (T supplier(DependencyResolver context), {String? name, List< Type> ? types, String scope = ScopeType.singleton, bool lazy = false, bool primary = false, bool fallback = false, bool autowireCandidate = true, bool defaultCandidate = true, int? order, String? description, List<String> aliases = const [], List<String> dependsOn = const []}) → void -
Adds a bean of type
T, created bysupplier, before refresh. -
registerShutdownHook(
) → void -
Closes the context when the process is asked to stop (Ctrl+C or a
kill), so that the beans release their resources.override -
removeApplicationListener(
GenericApplicationListener listener) → void -
Removes a listener added with addApplicationListener; it receives
no more events.
override
-
restart(
) → void -
Brings the lifecycle beans back to the state right after refresh,
typically after pause, then publishes
ContextRestartedEvent.override -
start(
) → void -
Starts every Lifecycle bean that is not running, also those that
are not auto-startup, then publishes
ContextStartedEvent. Throws aStateErrorunless the context is active.override -
stop(
) → void -
Stops every running Lifecycle bean, keeping the beans themselves,
then publishes
ContextStoppedEvent; start starts them again. Throws aStateErrorunless the context is active.override -
toString(
) → String -
A string representation of this object.
override
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited
Constants
- applicationEventMulticasterBeanName → const String
- The bean name of the object that delivers events to listeners.
- beanIntrospectorBeanName → const String
- The bean name under which the context registers its introspector.
- conversionServiceBeanName → const String
-
The bean name of a
ConversionServicethat replaces the environment's for converting@Valuetexts to their target types. - defaultTaskExecutorBeanName → const String
-
The bean name of the
TaskExecutorthat@Asynclisteners use when there are several executors and none is@Primary(Spring'sAsyncExecutionAspectSupport.DEFAULT_TASK_EXECUTOR_BEAN_NAME). - environmentBeanName → const String
-
The bean name under which the context registers its environment,
so it can be injected as
Environmentor looked up by name. - lifecycleProcessorBeanName → const String
- The bean name of the object that starts and stops the Lifecycle beans.
- messageSourceBeanName → const String
-
The bean name of the context's
MessageSource.