SpringApplication class
Starts an application: reads its configuration, creates its beans and runs its startup tasks, in a fixed and documented order.
A program built from beans needs the same steps every time: collect properties from the command line, the environment and the config files, set the log levels, create the context with the application's beans and the beans its libraries add, report a failed start in a readable way, and run the startup tasks. This class does all of that.
Most applications never create one. With @SpringBootApplication()
on main, the generator writes a springApplication getter (a new
instance with the application's modules and the auto-configuration of
its dependencies) and runApplication(args), which calls run. Reach
for this class directly to register listeners for the early events,
to set default properties, or to end the process with an exit code
(exit); tests usually go through spring_boot_starter_test.
What run does, in order:
- Publishes ApplicationStartingEvent. Adds the command-line
arguments, the
--dart-definevalues and the OS environment variables as property sources. - Reads
lib/resources/application.properties(or.yml), theapplication-{profile}files, imports and profile groups, then publishes ApplicationEnvironmentPreparedEvent. - Applies
logging.level.*to SpringLog (see applyLoggingLevels) and prints the banner. - Creates the context from modules, then autoConfigurations, so
a
@ConditionalOnMissingBean()of a library sees the application's beans. Registers ApplicationArguments as a bean and the binding of@ConfigurationProperties, runs the initializers, publishes ApplicationContextInitializedEvent and ApplicationPreparedEvent, then creates the beans. - Logs
Starting app using Dart 3.9.0 with PID 42(in Flutter,using Flutter 3.47.7 (Dart 3.13.5)), the active profiles andStarted app in 0.042 secondsat INFO (off withspring.main.log-startup-info=false), then publishes ApplicationStartedEvent. - Calls the
ApplicationRunnerandCommandLineRunnerbeans one after another, sorted by@Order, each finishing (itsFutureincluded) before the next starts. Then publishes ApplicationReadyEvent.
When a step fails, ApplicationFailedEvent is published and an
APPLICATION FAILED TO START report explains the error (from the
failureAnalyzers and the FailureAnalyzer beans first, then the
built-in analysis); then the error is rethrown. A failing runner is
reported as Application run failed and the context is closed.
SpringApplicationEvent explains which listeners receive which event.
Two more properties change the context:
spring.main.lazy-initialization=true creates every singleton on
first use (LazyInitializationBeanFactoryPostProcessor), and
spring.main.allow-bean-definition-overriding=true lets a bean
definition replace another of the same name (off by default).
// bin/main.dart: the generated getter, with a listener for an event
// that happens before any bean exists.
@SpringBootApplication()
void main(List<String> args) => (springApplication
..addListener<ApplicationEnvironmentPreparedEvent>(
(event) => log.info(event.environment.activeProfiles),
))
.run(args);
// Without the generator, from a module written by hand:
final context = SpringApplication([appBeans]).run(args);
Spring (Java):
ConfigurableApplicationContext context =
SpringApplication.run(App.class, args);
Constructors
-
SpringApplication(List<
BeanModule> modules, {List<BeanModule> autoConfigurations = const [], Map<BeanModule, AutoConfigurationModule> autoConfigurationMetadata = const {}, List<Type> exclude = const [], List<String> excludeName = const [], bool registerShutdownHook = false, List<ApplicationContextInitializer> initializers = const [], List<FailureAnalyzer> failureAnalyzers = const [], List<GenericApplicationListener> listeners = const [], Map<String, Object?> defaultProperties = const {}, List<String> additionalProfiles = const [], List<EnvironmentPostProcessor> environmentPostProcessors = const [], Map<String, String> dartDefines = const {}, Banner? banner, BannerMode bannerMode = BannerMode.console, ResourceLoader? resourceLoader, String? fingerprint, void out(String line)?}) -
An application made of its own
modulesand theautoConfigurationsof its libraries.
Properties
-
additionalProfiles
→ List<
String> -
Profiles that are always active, on top of those configured with
spring.profiles.active.final -
autoConfigurationMetadata
→ Map<
BeanModule, AutoConfigurationModule> -
The
@AutoConfigurationModuleannotation of each of autoConfigurations, whoseorder,beforeandafterdecide the order of registration. A module without an entry has order0and no constraints.final -
autoConfigurations
→ List<
BeanModule> -
The auto-configuration modules of the libraries, registered after
modules so their conditions see the application's beans.
final
-
The banner printed at startup when there is no banner file.
final
-
Where the banner goes; BannerMode.console by default. The property
spring.main.banner-mode(off,consoleorlog) wins when set.final -
dartDefines
→ Map<
String, String> -
Values given at build time with
--dart-define=KEY=value(or-DKEY=valuefordart compile/dart run), as properties.final -
defaultProperties
→ Map<
String, Object?> -
Properties with the lowest precedence: every other source, config
files included, overrides them.
no setter
-
environmentPostProcessors
→ List<
EnvironmentPostProcessor> -
Code that changes the properties or profiles before the context is
created, some before the config files are read and some after,
depending on their order. See EnvironmentPostProcessor.
final
-
exclude
→ List<
Type> -
@AutoConfigurationclasses whose beans are not registered, from@SpringBootApplication(exclude:). A type that is not an auto-configuration class fails the start.final -
excludeName
→ List<
String> -
Names of auto-configuration classes or modules that are not
registered, from
@SpringBootApplication(excludeName:). The propertyspring.autoconfigure.excludeadds more at run time. Unknown names are ignored.final -
failureAnalyzers
→ List<
FailureAnalyzer> -
Analyzers asked first when the start fails, before the
FailureAnalyzerbeans of the context and the built-in analysis.final - fingerprint → String?
-
A hash of the generated code the application was built from, written
by the generator.
final
- hashCode → int
-
The hash code for this object.
no setterinherited
-
initializers
→ List<
ApplicationContextInitializer> -
Code that prepares the context before its beans are created: add
post-processors or property sources, register ready-made objects as
beans. Run in
Orderedorder (unordered ones last). Test tools use them; see ApplicationContextInitializer.final -
listeners
→ List<
GenericApplicationListener> -
The listeners registered on the application, from the constructor and
addListeners; an unmodifiable copy.
no setter
-
modules
→ List<
BeanModule> -
The application's own bean modules, registered first and in this
order. The generator passes one module with every bean of the
package.
final
- out → void Function(String line)?
-
Where the failure report of a failed start goes instead of the log;
for a tool that shows it somewhere else, or a test that checks it.
final
- registerShutdownHook → bool
-
Whether the context is closed cleanly when the process gets SIGINT
(Ctrl+C) or SIGTERM, so
@PreDestroymethods andContextClosedEventlisteners run before the process ends.final - resourceLoader → ResourceLoader?
-
Reads the config files, the banner file and
resources:resources; aDefaultResourceLoaderby default. In Flutter, pass a loader that reads assets and start with runAsync, since assets can only be read asynchronously.final - runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
addListener<
E> (void listener(E event), {int order = Ordered.lowestPrecedence}) → void -
Registers
listeneron the application for the events of typeE, such as ApplicationStartingEvent, which no bean can receive. -
addListeners(
Iterable< GenericApplicationListener> listeners) → void - Registers listeners on the application itself, for the next runs.
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
reload(
ConfigurableApplicationContext running, {bool runners = true}) → ConfigurableApplicationContext -
After a hot reload, returns a context built from the current code:
runningitself when its beans did not change, or a restarted one. -
reloadAsync(
ConfigurableApplicationContext running, {bool runners = true}) → Future< ConfigurableApplicationContext> - The asynchronous form of reload, for Flutter and for code that uses runAsync.
-
run(
List< String> args, {Map<String, String> ? systemEnvironment, Map<String, Object?> properties = const {}, List<String> additionalProfiles = const [], SpringApplication hotReload()?}) → ConfigurableApplicationContext -
Starts the application with the program arguments
argsand returns the running context. -
runAsync(
List< String> args, {Map<String, String> ? systemEnvironment, Map<String, Object?> properties = const {}, List<String> additionalProfiles = const [], SpringApplication hotReload()?}) → Future<ConfigurableApplicationContext> -
Starts the application like run, and completes once every runner
has finished, as Spring Boot's
rundoes. -
setDefaultProperties(
Map< String, Object?> properties) → void -
Replaces all of defaultProperties with
properties, for the next runs. -
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited
Static Methods
-
applyLoggingLevels(
ConfigurableEnvironment environment) → void -
Sets the levels of SpringLog from the
logging.level.*andlogging.group.*properties ofenvironment. -
exit(
ConfigurableApplicationContext context, [List< ExitCodeGenerator> exitCodeGenerators = const []]) → int -
Closes
contextand returns the code the process should exit with. -
exitCodeOf(
Object error) → int? -
The exit code a failed run chose for
error, the error run or runAsync threw;nullwhen it chose none.
Constants
- dartDefinesPropertySourceName → const String
-
The name of the property source that holds dartDefines,
dartDefines. -
debugLoggers
→ const List<
String> -
The loggers
--debug(ordebug=true) turns to debug: the container (spring_core_dart), Boot (spring_boot_dart) and the web server (spring.web.server), like Boot's debug oforg.springframework,org.springframework.bootand the embedded server. Levels inlogging.level.*win. -
predefinedLoggerGroups
→ const Map<
String, List< String> > -
The log groups that exist without
logging.group.*, like Boot'swebandsql:logging.level.web=debugsets the web starters' loggers (spring.web.*,spring.websocket.*),logging.level.sqlthose of JDBC (spring.jdbc.core.JdbcTemplate,spring.jdbc.core.StatementCreatorUtils). Alogging.group.webof the application replaces the predefined list. -
traceLoggers
→ const List<
String> -
The loggers
--trace(ortrace=true) turns to trace; the same selection as debugLoggers.tracewins overdebug.