SpringApplication

SpringApplication starts an application: it reads the configuration, creates the beans with those of the starters, and runs the start-up tasks, in a fixed and documented order. It is Spring Boot's SpringApplication.

Most applications never create one. With @SpringBootApplication() on main, the generator writes a springApplication getter and the functions that call it.

Why

A program built from beans needs the same steps every time: collect the properties, set the log levels, create the context with the application's beans and its libraries' beans, report a failed start in a readable way, run the start-up work. Doing it by hand is a page of code that each project gets slightly wrong. SpringApplication does it once, with Spring Boot's order, so starters and tests can rely on it.

Example

// bin/main.dart
import 'package:spring_boot_dart/spring_boot_dart.dart';

import 'spring_gen/main.spring.dart';

@SpringBootApplication()
void main(List<String> args) => runApplication(args);

The generated file holds, among others:

// bin/spring_gen/main.spring.dart (generated)
SpringApplication get springApplication => SpringApplication(
      [$application],                      // every bean of the package
      autoConfigurations: [                // found in the dependencies
        springBootStarterLoggingAutoConfiguration,
        springBootAutoConfiguration,
      ],
      dartDefines: {...},                  // the --dart-define values that were given
      fingerprint: ...,                    // for hot reload: debug and profile builds only
    );

ConfigurableApplicationContext runApplication(List<String> args) => ...;
Future<ConfigurableApplicationContext> runApplicationAsync(List<String> args) => ...;
// main.spring.debug.dart (debug and profile builds only):
ConfigurableApplicationContext reloadApplication(ConfigurableApplicationContext context, {bool runners = true}) => ...;

To change something, use the getter:

// A listener for an event that happens before any bean exists.
@SpringBootApplication()
void main(List<String> args) => (springApplication
      ..addListener<ApplicationEnvironmentPreparedEvent>(
        (event) => print(event.environment.activeProfiles),
      ))
    .run(args);

@SpringBootApplication

Parameter Type Meaning
exclude List<Type> Auto-configuration classes not to apply. A Type is compared by its simple name
excludeName List<String> Auto-configuration classes or modules not to apply, by name ('JacksonAutoConfiguration', 'springBootAutoConfiguration', 'package:x/src/y.dart#CacheAutoConfiguration')

It goes on the top-level main function of bin/ (or lib/main.dart in Flutter). There is one per package. See Auto-configuration and The generator: @SpringBootApplication.

The steps of a start

run(args) does, in order:

  1. Starting. Publishes ApplicationStartingEvent. Adds the command-line arguments, the --dart-define values, the OS environment variables, run(properties:) and the default properties as property sources, and ${random.*}.
  2. The environment. Runs the early EnvironmentPostProcessors (SPRING_APPLICATION_JSON), reads the config files (locations, profiles, imports), runs the other post-processors (the renamed properties check), then publishes ApplicationEnvironmentPreparedEvent.
  3. Logging. Applies logging.level.* to SpringLog (see Logging levels), then prints the banner.
  4. The context. Creates the context from the application's modules, then the auto-configurations in their order, so a starter's @ConditionalOnMissingBean sees the application's beans. Registers ApplicationArguments as a bean and the binding of @ConfigurationProperties. Runs the initializers, publishes ApplicationContextInitializedEvent and ApplicationPreparedEvent.
  5. The beans. Refreshes the context: every singleton is created (unless lazy), ContextRefreshedEvent is published.
  6. Waiting. Beans that implement AsyncStartup (the web server binding its port) are awaited. One that fails fails the start: no runner, no ApplicationReadyEvent.
  7. Started. Logs Started neon-books in 0.07 seconds, publishes ApplicationStartedEvent and LivenessState.correct.
  8. Runners. Calls the ApplicationRunner and CommandLineRunner beans one after another (see Runners).
  9. Ready. Publishes ApplicationReadyEvent and ReadinessState.acceptingTraffic.

When a step fails, ApplicationFailedEvent is published, an APPLICATION FAILED TO START report is logged (see Failure reports) and the error is rethrown.

run and runAsync

Call Config files Returns Use
runApplication(args) / springApplication.run(args) read synchronously as soon as the synchronous part is done; runners returning a Future go on afterwards servers and tools on the Dart VM
runApplicationAsync(args) / springApplication.runAsync(args) read asynchronously (Flutter assets, HTTP imports) after the last runner, as Spring Boot's run Flutter, HTTP config, main that waits for the start

runAsync also creates the beans with refreshAsync(), so asynchronous @PostConstruct methods are awaited before the runners start.

Both take the same named parameters, meant for tests and tools:

Parameter Meaning
systemEnvironment Replaces the OS environment variables
properties Properties above every other source, the command line included
additionalProfiles Profiles activated for this launch, after the application's own additionalProfiles
hotReload The application as the code is now (the generated functions pass () => springApplication), for hot reload and for starting the same application in another isolate

With hotReload, the context has an ApplicationLaunch bean (springApplicationLaunch): how the application was started, with its arguments, properties and profiles, so that the same one can be started again. The web server's pool of isolates starts each of its isolates with it (ApplicationLaunch.start). An application started with the generated runApplication or runApplicationAsync has the bean; one started with a plain springApplication.run(args) does not, and its server cannot add isolates. What hotReload returns crosses to the other isolate, so it must not use anything from around it.

The constructor

The generator fills modules, autoConfigurations, autoConfigurationMetadata, exclude, excludeName, dartDefines and fingerprint. The other parameters are for code that creates the application itself.

Parameter Default Meaning
modules required The application's own bean modules, registered first
autoConfigurations [] The starters' modules, registered after, in auto-configuration order
autoConfigurationMetadata {} The @AutoConfigurationModule of each module: order, before, after, factories
exclude, excludeName [] Auto-configurations not to apply
registerShutdownHook false Close the context on SIGINT or SIGTERM; spring.main.register-shutdown-hook wins (see Shutdown)
initializers [] ApplicationContextInitializers run before the beans are created, in Ordered order
failureAnalyzers [] Asked first when the start fails, also before any bean exists
listeners [] Listeners of every start-up event; also addListener and addListeners
defaultProperties {} The lowest property source; also setDefaultProperties
additionalProfiles [] Profiles always active, before the configured ones
environmentPostProcessors [] Code that changes the environment before any bean exists
addressResolvers [] RemoteAddressResolvers asked before the built-in ones for the configuration's downloads (themes, images); the context has the chain as the remoteAddresses bean
applicationStartup ApplicationStartup.none Records the steps of the start (spring.boot.application.starting, ...environment-prepared, ...context, one spring.beans.instantiate per bean); give a BufferingApplicationStartup to measure
dartDefines {} The --dart-define values, a property source below the command line
banner none The banner printed when there is no banner file
bannerMode BannerMode.console Where the banner goes; spring.main.banner-mode wins
resourceLoader DefaultResourceLoader Reads config files, the banner and resources:; pass one with a ProtocolResolver for other locations
fingerprint none A hash of the generated code, for hot reload; the generator passes it in debug and profile builds only (it is in main.spring.debug.dart)
out the log Receives the failure report text instead of the log

progressListener (a field) is told how far the start has come, for a splash screen: a StartupProgress with done, total and fraction (from 0 to 1, never going back), counting bean definitions created and runners called.

factories (a field) is a SpringFactories with the factories of every auto-configuration module, for code that runs before any bean exists: springApplication.factories.load<ThemeDesign>() gives those of one type. The context has it as the springFactories bean. See Factories.

The startup log

At INFO, under spring_boot_dart.SpringApplication:

Starting neon-books using Dart 3.13.5 with PID 4242
The following 1 profile is active: "prod"
Started neon-books in 0.07 seconds

In Flutter the first line says using Flutter 3.50.0 (Dart 3.14.0). Without an active profile: No active profile set, falling back to 1 default profile: "default". The name is spring.application.name, application when not set. spring.main.log-startup-info=false turns these lines off. Without spring_boot_starter_logging, SpringLog writes INFO and above to the console, so the lines show either way.

The banner

A banner is printed before the context is created:

  1. the file of spring.banner.location (resources:banner.txt by default, that is lib/resources/banner.txt);
  2. else SpringApplication(banner:);
  3. else the built-in SpringBootBanner.

spring.main.banner-mode (or bannerMode:) is console (printed, the default), log (logged at INFO) or off (false, what YAML makes of off, works too). In the file, ${spring-boot.version}, ${spring-boot.formatted-version} and any other ${...} are replaced. With runAsync, a banner that can only be read asynchronously, such as a Flutter asset, is printed too.

# lib/resources/banner.txt
NEON Books ${spring-boot.formatted-version} on port ${server.port:8080}

Lazy start

spring.main.lazy-initialization=true creates every singleton on first use instead of at start-up. The start is shorter, which helps command-line tools and mobile apps, but a broken bean fails later, when it is first used.

A LazyInitializationExcludeFilter bean keeps the beans it excludes eager:

// The cache warmer must start with the application, even with lazy start.
@Bean()
LazyInitializationExcludeFilter eagerWarmer() =>
    LazyInitializationExcludeFilter.forBeanTypes([CacheWarmer]);

LazyInitializationExcludeFilter.of((name, definition, type) => ...) decides per bean. A bean marked @Lazy(false) stays eager too.

Bean overriding

Two bean definitions with the same name stop the start:

The bean 'cache', defined in package:shop/cache.dart#CacheConfiguration, could not be registered. A bean with that name has already been defined and overriding is disabled.

spring.main.allow-bean-definition-overriding=true lets the later definition replace the earlier one.

Context initializers

An ApplicationContextInitializer changes the context before its beans are created: adds post-processors or property sources, registers ready-made objects. Test tools use them:

SpringApplication(
  [appBeans],
  initializers: [
    ApplicationContextInitializer.of(
      (context) => context.beanFactory.registerSingleton('clock', FixedClock()),
    ),
  ],
).run(args);

In Spring (Java)

SpringApplication application = new SpringApplication(NeonBooks.class);
application.setDefaultProperties(Map.of("server.port", "8080"));
application.setAdditionalProfiles("mobile");
application.addListeners(event -> ...);
application.run(args);

Differences:

See also