Auto-configuration and starters

A starter is a library that brings ready-made beans: add it to pubspec.yaml, run build_runner, and its feature is there with no code of yours. It ships them as auto-configuration: beans registered after the application's own, guarded by conditions so that your own bean always wins.

Why

A web server, a cache or a logging setup needs a dozen beans wired the right way. Writing them in every application is repetitive and error-prone. With auto-configuration, the library writes them once, and each application overrides only what it wants: declare your own Cache bean and the starter's @ConditionalOnMissingBean(Cache) backs off.

Example

A starter neon_cache:

// lib/spring_auto_configuration.dart of package neon_cache (the file name is fixed)
import 'package:spring_boot_dart/spring_boot_dart.dart';

import 'spring_gen/src/cache.spring.dart';

@AutoConfigurationModule(requires: '^0.7.0')
final BeanModule neonCacheAutoConfiguration = $neonCacheBeans;
// lib/src/cache.dart of neon_cache
@AutoConfiguration()
class CacheAutoConfiguration {
  @Bean()
  @ConditionalOnMissingBean(Cache)                       // the application's own Cache wins
  @ConditionalOnProperty('neon.cache.enabled', matchIfMissing: true)
  Cache cache(@Value(r'${neon.cache.size:100}') int size) => InMemoryCache(size);
}

An application that depends on neon_cache gets a Cache bean with no code. One that declares its own gets only its own:

// The application's bean: the starter's cache() is not registered.
@Bean()
Cache cache() => RedisCache();

How starters are found

When an application with @SpringBootApplication() is built, the generator walks every package of its dependency graph, direct and transitive, reads lib/spring_auto_configuration.dart where there is one, and lists the annotated modules in the generated springApplication:

// bin/spring_gen/main.spring.dart of the application (generated)
SpringApplication get springApplication => SpringApplication(
      [$application],
      autoConfigurations: [
        neonCacheAutoConfiguration,   // found in neon_cache
        springBootAutoConfiguration,  // spring_boot_dart
      ],
      // only where a starter sets order, before, after or factories
      autoConfigurationMetadata: {
        neonCacheAutoConfiguration: AutoConfigurationModule(order: 10),
      },
    );

@AutoConfigurationModule

On a public top-level BeanModule variable of lib/spring_auto_configuration.dart.

Parameter Default Meaning
order 0 The position among the modules, lower first (Spring Boot's @AutoConfigureOrder)
before [] Modules, or @AutoConfiguration classes by short name, that must be registered after this one
after [] Modules or classes that must be registered before this one: ['springBootAutoConfiguration']
requires null: any The spring_boot_dart versions the starter works with, as a pub range (^0.7.0). A mismatch stops the build (see Versions)
build null: always An AutoConfigurationBuild: a property of the application's configuration decides whether the module is in the build at all
platform null: everywhere A ModulePlatform: native, web or server. On another platform the compiler drops the module and everything only it reaches
factories [] Constants the application finds by type before any bean exists. See Factories

@AutoConfiguration() marks a configuration class of a starter; it is a @Configuration whose @Bean methods are registered with auto-configuration.

The order of registration

  1. The application's own classes, first.
  2. The auto-configuration modules, sorted as Spring Boot's AutoConfigurationSorter: by order, modules of the same order by name, then before and after move them. A cycle stops the start with AutoConfigure cycle detected between .... Unknown names are ignored.
@AutoConfigurationModule(
  order: 10,
  after: ['springBootAutoConfiguration'],    // a module or an @AutoConfiguration class
  before: ['neonMetricsAutoConfiguration'],
)
final BeanModule neonCacheAutoConfiguration = $neonCacheBeans;

Bean conditions are decided class by class in that order, so @ConditionalOnMissingBean sees what the application declared, including the beans of its @Imported registrars. See Conditions.

Excluding auto-configuration

When a starter's beans are not wanted, exclude them before their conditions run:

@SpringBootApplication(
  exclude: [CacheAutoConfiguration],                     // by class
  excludeName: ['springBootStarterCacheAutoConfiguration'], // a module or a class name
)
void main(List<String> args) => runApplication(args);
# Adds to the annotation, at run time: comma list or YAML list
spring.autoconfigure.exclude=JacksonAutoConfiguration,CacheAutoConfiguration

The built-in ones are JacksonAutoConfiguration, ValidationAutoConfiguration, MessageSourceAutoConfiguration, LifecycleAutoConfiguration, ApplicationAvailabilityAutoConfiguration, JsonSchemaAutoConfiguration and ObservationAutoConfiguration (see Built-in beans).

Modules left out of the build

A feature only developers use (a debug panel) should not ship in a release. build: lets the application's configuration decide, when the generator runs, whether the module is in the application at all:

@AutoConfigurationModule(
  build: AutoConfigurationBuild('spring.flutter.debug.enabled'),
)
final BeanModule debugAutoConfiguration = BeanModule(/* ... */);

The property is read from application.yml and application.properties without a profile, when build_runner runs:

Property The module
true in every build
false in no build: no code at all
not set whenMissing

whenMissing is a BuildInclusion:

Value Meaning
notInRelease (default) In debug and profile builds; a release compiles it away (dart.vm.product)
always In every build
never In no build

A module the build puts in on a condition keeps its order, before and after. A build property set only in a profile file is warned about, since the build does not read profile files. See Modules left out of the build.

Modules of one platform

Some code works on one platform only. A web server needs dart:io, which a browser does not have; code that reaches the browser through dart:js_interop cannot run on a server. platform: keeps a module to where its code works:

@AutoConfigurationModule(platform: ModulePlatform.native)
final BeanModule neonServerAutoConfiguration = BeanModule(/* ... */);
ModulePlatform Where the module is
native Where dart:io exists: the Dart VM, an AOT executable, a Flutter app on a phone or a desktop. Not a browser
web A browser, compiled to JavaScript or WebAssembly
server The Dart VM or an AOT executable: dart:io exists and Flutter's dart:ui does not. Never a Flutter app, never a browser. For code that must not ship in an app, which anyone can read: an API that needs a secret key
not given Everywhere

The generated application lists such a module under a constant the compiler knows (dart.library.io, dart.library.js_interop, dart.library.ui). On another platform the constant is false: the compiler drops the module and all that only it reaches. So a Flutter web app whose dependencies bring spring_boot_starter_web carries no server code, and nothing has to be excluded by hand.

Spring has no counterpart: a JVM application runs on one platform.

Factories

Beans exist once the context is created. A few things a starter adds must work earlier, while the environment is prepared or a Flutter app shows its splash. The design library a Flutter theme is read with is one: the themes are read for the splash, before any bean exists. A starter lists such things as constants in factories:

@AutoConfigurationModule(factories: [OceanThemeDesign()])
final BeanModule oceanAutoConfiguration = $oceanBeans;

The code that needs them asks for a type:

// In a listener of ApplicationEnvironmentPreparedEvent
final designs = event.springApplication.factories.load<ThemeDesign>();

Use factories only for what must exist before the beans. Everything else stays a bean, which an application can replace.

Writing your own starter

Any package can be a starter.

  1. Declare the module in lib/spring_auto_configuration.dart: a public top-level BeanModule variable with @AutoConfigurationModule.
  2. Describe the beans, with the generator (@AutoConfiguration, @Bean and conditions, scanned by a @ComponentScan in the starter) or as hand-written BeanDefinitions. A hand-written definition needs a source (library#Class) or a factoryMethodName for its bean conditions to be decided in order; one with neither is decided at once.
  3. Publish the generated code. The generator writes files only into the package being built, never into dependencies. Run dart run build_runner build in the starter and publish its *.spring.dart files.
  4. Test it with ApplicationContextRunner from spring_boot_starter_test: alone, with an application bean that makes it back off, and with properties that switch it off.
// test/cache_auto_configuration_test.dart
test('backs off when the application has a Cache', () {
  const ApplicationContextRunner()
      .withAutoConfiguration(neonCacheAutoConfiguration)
      .withBean<Cache>(RedisCache.new)
      .run((context) {
    expect(context, hasSingleBean<Cache>());
    expect(context.getBean<Cache>(), isA<RedisCache>());
  });
});

Keep the starter's third-party constraints wide (dio: '>=5.0.0 <7.0.0') so applications can resolve them together with other starters.

Starters of the family

Starter What adding the dependency gives
spring_boot_starter_logging Console output with patterns, log files with rollover, logging.* properties, a LogBuffer
spring_boot_starter_web An HTTP server: @RestController, JSON bodies, @Valid, ProblemDetail errors, SSE, filters, CORS
spring_boot_starter_security A security filter chain, HTTP Basic, form login, sessions, CSRF, JWT resource servers
spring_boot_starter_feign HTTP clients from annotated interfaces
spring_boot_starter_websocket WebSocket clients and endpoints
spring_boot_starter_cache @Cacheable, @CachePut, @CacheEvict, a CacheManager
spring_boot_starter_scheduling @Scheduled methods and a TaskScheduler
spring_boot_starter_data Repositories and SQL databases
spring_boot_starter_actuator Health, info, metrics and other management endpoints
spring_boot_starter_flutter Flutter apps: SpringApplicationWidget, beans in widgets, themes, platform profiles
spring_boot_starter_test (dev) springBootTest, ApplicationContextRunner, bean overrides, captureLogs

In Spring (Java)

# META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
com.neon.cache.CacheAutoConfiguration
@AutoConfiguration(after = JacksonAutoConfiguration.class)
@AutoConfigureOrder(10)
class CacheAutoConfiguration { ... }

Differences:

See also