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),
},
);
- Discovery happens at build time, not by scanning a classpath at start-up. After adding a starter, run
build_runneragain. - Only
@SpringBootApplicationapplications discover modules. An application that creates its context by hand lists the modules itself.
@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
- The application's own classes, first.
- The auto-configuration modules, sorted as Spring Boot's
AutoConfigurationSorter: byorder, modules of the same order by name, thenbeforeandaftermove them. A cycle stops the start withAutoConfigure 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
- A
Typeinexcludeis compared by its simple name, so classes of the same name in different libraries are excluded together. excludeNameand the property take a module name (springBootAutoConfiguration), a short class name, orpackage:x/src/y.dart#CacheAutoConfiguration.- Excluding a class removes its beans, its imported registrars and selectors, and its conditional
@PropertySources; configuration classes it@Imports stay. Excluding a module removes all of it. - Excluding a type that is no auto-configuration stops the start; an unknown name is ignored.
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.
- It is not a runtime condition. On the other platform the module's beans are not skipped; they are not in the program.
platform:combines withbuild:; the module is in when both say so.- A program compiled with
-DSPRING_ALL_PLATFORMS=truekeeps every module whatever the platform: for server code run as JavaScript under Node on purpose. - Use it for a whole module. A bean that differs by platform inside a module that is everywhere is chosen with a conditional import, as most starters do.
- Which modules of the family are marked is listed on Modules of one platform.
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>();
SpringApplication.factoriesis aSpringFactoriesthat holds the factories of every module of the application.load<T>()gives those of typeT: byOrderedwhere they implement it, else in the order of the modules. It is empty when no starter has one.- The context has the same object as the
springFactoriesbean. - Each factory is a public constant: a
constconstructor call with literal arguments (a named constructor too), a top-levelconstvariable or astatic constfield. The generator copies it into the generatedspringApplication; a factory in any other form stops the build with an explanation. - An application gets the factories of a starter when it is generated: run
build_runneragain after adding a starter that has some.
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.
- Declare the module in
lib/spring_auto_configuration.dart: a public top-levelBeanModulevariable with@AutoConfigurationModule. - Describe the beans, with the generator (
@AutoConfiguration,@Beanand conditions, scanned by a@ComponentScanin the starter) or as hand-writtenBeanDefinitions. A hand-written definition needs asource(library#Class) or afactoryMethodNamefor its bean conditions to be decided in order; one with neither is decided at once. - Publish the generated code. The generator writes files only into the package being built, never into dependencies. Run
dart run build_runner buildin the starter and publish its*.spring.dartfiles. - Test it with
ApplicationContextRunnerfromspring_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:
- The module, not the class, is the unit:
order,beforeandafterare on@AutoConfigurationModule, and classes can be named in them by short name. - Starters are discovered at build time; a new starter needs a rebuild.
- A
Typeinexcludeis compared by its simple name. build:(modules left out of a release) has no Spring counterpart.factoriesare the entries of Spring'sMETA-INF/spring.factories, whichSpringFactoriesLoader.loadFactories(type, classLoader)finds on the class path. Dart has no class path to scan, so the generator copies the constants into the generated application.