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:

  1. Publishes ApplicationStartingEvent. Adds the command-line arguments, the --dart-define values and the OS environment variables as property sources.
  2. Reads lib/resources/application.properties (or .yml), the application-{profile} files, imports and profile groups, then publishes ApplicationEnvironmentPreparedEvent.
  3. Applies logging.level.* to SpringLog (see applyLoggingLevels) and prints the banner.
  4. 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.
  5. 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 and Started app in 0.042 seconds at INFO (off with spring.main.log-startup-info=false), then publishes ApplicationStartedEvent.
  6. Calls the ApplicationRunner and CommandLineRunner beans one after another, sorted by @Order, each finishing (its Future included) 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 modules and the autoConfigurations of 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 @AutoConfigurationModule annotation of each of autoConfigurations, whose order, before and after decide the order of registration. A module without an entry has order 0 and 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
bannerMode → BannerMode
Where the banner goes; BannerMode.console by default. The property spring.main.banner-mode (off, console or log) wins when set.
final
dartDefines → Map<String, String>
Values given at build time with --dart-define=KEY=value (or -DKEY=value for dart 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>
@AutoConfiguration classes 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 property spring.autoconfigure.exclude adds more at run time. Unknown names are ignored.
final
failureAnalyzers → List<FailureAnalyzer>
Analyzers asked first when the start fails, before the FailureAnalyzer beans 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 Ordered order (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 @PreDestroy methods and ContextClosedEvent listeners run before the process ends.
final
resourceLoader → ResourceLoader?
Reads the config files, the banner file and resources: resources; a DefaultResourceLoader by 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 listener on the application for the events of type E, 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: running itself 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 args and 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 run does.
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.* and logging.group.* properties of environment.
exit(ConfigurableApplicationContext context, [List<ExitCodeGenerator> exitCodeGenerators = const []]) → int
Closes context and 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; null when it chose none.

Constants

dartDefinesPropertySourceName → const String
The name of the property source that holds dartDefines, dartDefines.
debugLoggers → const List<String>
The loggers --debug (or debug=true) turns to debug: the container (spring_core_dart), Boot (spring_boot_dart) and the web server (spring.web.server), like Boot's debug of org.springframework, org.springframework.boot and the embedded server. Levels in logging.level.* win.
predefinedLoggerGroups → const Map<String, List<String>>
The log groups that exist without logging.group.*, like Boot's web and sql: logging.level.web=debug sets the web starters' loggers (spring.web.*, spring.websocket.*), logging.level.sql those of JDBC (spring.jdbc.core.JdbcTemplate, spring.jdbc.core.StatementCreatorUtils). A logging.group.web of the application replaces the predefined list.
traceLoggers → const List<String>
The loggers --trace (or trace=true) turns to trace; the same selection as debugLoggers. trace wins over debug.