Differences from Spring
Spring (Java) finds your beans when the application starts: it scans the classpath for annotated classes, reads their annotations and constructors with reflection, and creates proxies as new classes in memory. Spring for Dart keeps the programming model, the same annotations with the same meaning, but moves that discovery to build time. spring_core_dart_generator reads the annotations while build_runner runs and writes plain Dart code that creates and connects the objects. This page lists what that changes, why, and what stays the same.
Why
Dart has no reflection where apps run. dart:mirrors is not available in Flutter, in AOT-compiled executables or on the web, and Dart cannot create classes while a program runs. So everything Spring learns by looking at classes at start must be known before the program is compiled.
Most differences below follow from that one fact. Some are costs (you must run a build; the build sees only what is in the source). Some are gains (errors before the app runs; no start-up scanning; code that survives minification and tree shaking).
Example
The same service in both:
// Spring (Java): found at start by classpath scanning, created by reflection.
@Service
class Greeter {
Greeter(@Value("${greeting.suffix:!}") String suffix, Clock clock) { ... }
}
// Spring for Dart: the same annotations...
@Service()
class Greeter {
Greeter(@Value(r'${greeting.suffix:!}') this.suffix, this.clock);
final String suffix;
final Clock clock;
}
...and the build writes the code Spring would run by reflection (simplified: the real file uses import prefixes such as _i1.):
// lib/spring_gen/beans.spring.dart (generated)
BeanModule get $appBeans => BeanModule(r'appBeans', [
BeanDefinition<Greeter>(
name: r'greeter',
types: const [Greeter],
dependencies: const [
Dependency.value(r'${greeting.suffix:!}'),
Dependency(Clock, name: r'clock'),
],
create: (r) => Greeter(
r.value<String>(r'${greeting.suffix:!}'),
r.dependency<Clock>(name: r'clock'),
),
),
]);
The context reads this list when it starts. It still resolves the value, finds the Clock bean, checks conditions and runs the lifecycle at run time, as Spring does. Only the discovery and the construction code are generated.
At a glance
| Topic | Spring (Java) | Spring for Dart |
|---|---|---|
| Finding beans | Classpath scanning at start | @ComponentScan() on a top-level variable: the build scans that file's directory and below |
| Creating beans | Reflection on constructors, fields, setters | Generated constructor calls and closures |
| AOP proxies | JDK dynamic proxies or CGLIB subclasses, made at start | Proxy classes generated at build time |
Full @Configuration classes, @Lookup |
CGLIB subclasses at start | Generated subclasses |
| Introspection (JSON, validation, SpEL) | Reflection on any class | Generated descriptions, of what the build saw used |
| Auto-configurations | META-INF/spring/...AutoConfiguration.imports on the classpath |
lib/spring_auto_configuration.dart of each dependency, found through the package config |
| Factories of a starter, needed before the beans exist | META-INF/spring.factories on the classpath, read by SpringFactoriesLoader.loadFactories(type, classLoader) |
factories of @AutoConfigurationModule: public constants the generator copies into the generated springApplication |
| Leaving a module out of the binary | Not needed: unused classes cost little on the JVM | AutoConfigurationBuild: a build-time decision by a property |
| Resources | Files on the classpath | lib/resources/ embedded into the generated code |
--dart-define / system properties |
Any key at run time | A generated list of constant keys |
| Configuration metadata | spring-boot-configuration-processor, an annotation processor |
The spring_metadata builder |
| Wrong annotations | Mostly found at start | Found by the build, with the source location |
Discovery: build-time scanning instead of the classpath
Spring scans packages of the classpath at start. Here, a scan root is a top-level variable with @ComponentScan(); the build scans every class in that file's directory and below, and writes a BeanModule with one BeanDefinition per bean. A subdirectory with its own @ComponentScan is left to that scan. See @ComponentScan modules.
The scan options of Spring work, evaluated at build time: includeFilters, excludeFilters (by annotation, by assignable type, by regular expression on the class name), useDefaultFilters and lazyInit. FilterType.ASPECTJ and FilterType.CUSTOM do not exist: a custom filter would be code that runs during the scan, and the scan is the build.
What this gives:
- No scanning at start. The list of beans is a constant of the program. Start-up time does not grow with the number of classes, which matters for a Flutter app's first frame.
- Code that survives the compilers. Generated constructor calls work in AOT, in Flutter and on the web, and are not affected by minification. Nothing is looked up by name at run time.
What it costs:
- A build step. Every change to annotations needs
dart run build_runner build, orwatchrunning. Without it the annotations do nothing. - The bean set is what the source declared. A class cannot become a bean because a JAR appeared on the classpath; it must be in a scanned directory, a
@Beanmethod, an imported module or an auto-configuration of a dependency.
Proxies: generated, not made at run time
Spring makes AOP proxies at start, with JDK dynamic proxies for interfaces or CGLIB subclasses for classes. Dart cannot create classes at run time, so the generator writes a proxy class for each bean that may need one: an implementing proxy, or a subclass proxy for a class that can only be extended. At start, the context still decides which beans the pointcuts match; a bean nothing matches is not wrapped. See AOP proxies.
The same applies to the other places Spring uses CGLIB: full-mode @Configuration classes (so a @Bean method calling another returns the shared bean) and beans with @Lookup methods get generated subclasses.
What this costs, and how the generator limits it:
- Code size. A proxy class is code even when no advice ever matches. With
aop_prune(on by default), the application's build leaves out the proxy classes of beans that no advice of the application can match, and keeps only the advised members in the others. See AOP proxies: pruning and deferring. - Class shape. A proxy must be able to stand in for the bean. A
finalclass without an interface cannot be proxied: advice that matches it fails the start with the reason and what to change. Spring has a similar limit forfinalclasses with CGLIB. - Advice added without the build seeing it. With pruning, an advisor registered at run time in a way the build cannot read does not apply to what was left out. The generator keeps every proxy when it finds an advisor whose pointcut it cannot read.
Introspection: only what the build saw used
Spring's ObjectMapper, validation and SpEL use reflection on any object. Here they read generated descriptions (Introspection). To keep the program small, a class is described only for what the application does with it: the getters when it is written as JSON, the constructor and setters when it is read, the getters of constrained properties when it is validated, the methods when a SpEL expression may call them. See Only what runs: introspection.
The cost: a use the build cannot see, such as a value cast to Object and then written as JSON, finds a description without the part it needs. It fails with a message that names the class, the missing part and the fix, never with an empty object:
Bad state: Book is described without its getters, but it is written out as
JSON. The build described only what it saw used, and did not see that: add
@Introspected() to Book.
@Introspected() on a class keeps everything, as reflection would.
Auto-configurations: the package config instead of META-INF
Spring Boot reads META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports from every JAR on the classpath. Here the build of the @SpringBootApplication library looks at every package the application depends on, directly or not (read from the pubspec.yaml files, so a sibling in a pub workspace is not taken), and reads its lib/spring_auto_configuration.dart. Each top-level variable there with @AutoConfigurationModule is an auto-configuration. The generated springApplication lists them:
// lib/spring_gen/main.spring.dart (generated, simplified)
SpringApplication get springApplication => SpringApplication(
[$application],
autoConfigurations: [
springBootAutoConfiguration,
springBootStarterFlutterAutoConfiguration,
if (!const bool.fromEnvironment('dart.vm.product'))
springBootStarterFlutterDebugAutoConfiguration,
springBootStarterFlutterNavigationAutoConfiguration,
],
// ...
);
The list is in package order, then by name. SpringApplication sorts it at start by order, before and after, as Spring Boot's AutoConfigurationSorter does with @AutoConfigureOrder, @AutoConfigureBefore and @AutoConfigureAfter. exclude and excludeName of @SpringBootApplication and the property spring.autoconfigure.exclude still work at start. A starter can also declare which spring_boot_dart versions it accepts (requires:); a version outside the range fails the build. What a starter adds before the beans exist, Spring's META-INF/spring.factories, is the factories of its module: the generator copies those constants into springApplication, and one that is no public constant stops the build. See Auto-configurations.
Build conditions: a build-time analogue of conditions
Spring evaluates @Conditional, @Profile and @ConditionalOnProperty at start, and so does Spring for Dart: conditions are written into the bean definitions and decided when the context starts, with the full configuration, the profiles, --dart-define values and the environment.
There is one addition with no Spring counterpart. On the JVM, an auto-configuration that its conditions turn off costs a few unused classes. In a Flutter app every compiled-in line is shipped to users. So an @AutoConfigurationModule can take build: AutoConfigurationBuild('<property>'), and the generator decides by that property, read from the configuration files while it builds:
true: the module is in every build;false: the module is not in the program at all, nor anything only it reaches;- not set: by default in debug and profile builds only (
if (!const bool.fromEnvironment('dart.vm.product'))above), so a release build compiles it away.
spring_boot_starter_flutter's debug panel uses it with spring.flutter.debug.enabled. The property is read from the files only, never from the environment or --dart-define. See Modules left out of the build and Properties the build reads.
Spring's own build-time processing, Spring AOT for native images, goes further: it evaluates conditions and profiles at build time and fixes the bean set. Spring for Dart does not. Apart from AutoConfigurationBuild, conditions stay at run time, so a profile chosen when the app starts still changes its beans.
Resources: embedded instead of on the classpath
Spring loads classpath: resources from JARs. A Dart program has no classpath, and a Flutter app on the web has no file system. So the generator embeds the files of lib/resources/ into the generated code: text as text, other files as base64, files above 1 MB skipped with a warning. resources: locations, config files included, then work on every platform without declaring Flutter assets. See Embedded resources.
--dart-define: constant keys
A Java program reads any system property or environment variable by name at run time. A Dart program compiled for the web or AOT can read a --dart-define value only with a constant key: const String.fromEnvironment('KEY'). So the @SpringBootApplication output lists every property name the application may read, in both forms (shop.currency and SHOP_CURRENCY), from the placeholders in annotations, @ConditionalOnProperty names, @ConfigurationProperties fields and the keys of the config files:
// lib/spring_gen/main.spring.dart (generated, simplified)
dartDefines: {
if (const bool.hasEnvironment('LOGGING_LEVEL_ROOT'))
'LOGGING_LEVEL_ROOT': const String.fromEnvironment('LOGGING_LEVEL_ROOT'),
// ...
},
The cost: a key the build did not see, such as one built from a string at run time, cannot be set with --dart-define. Config files, the environment and the command line still set it. See --dart-define keys.
Errors at build time
Spring reports most mistakes when the context starts. The generator reports what it can see in the source while it builds, with the source location, and lists every independent problem of one build together:
- a pointcut expression that does not parse, with the position of the error;
- a validation constraint on a type it cannot check (
@Sizeon anint) or with invalid attributes; - a derived query whose name does not match the entity (
findByTitel: did you meantitle?), a@Querywhose parameters, placeholders, tables or columns do not match; - an injected field that cannot be set, a
@Lazynullable dependency, a private type the generated code cannot name; - a literal
@Value('asset:...')whose asset is not declared inpubspec.yaml; - typed theme and message keys that do not agree across files.
See Build-time checks.
Some checks still happen at start, as in Spring, because they depend on the whole application: a missing or ambiguous bean and a dependency cycle are reported when the context starts, before any of your objects is created.
An error in the sources never deletes the generated file: build_runner watch keeps the last good output, so files that import it do not turn red while you type. See Errors and the generated files.
Metadata for editors
Spring Boot writes META-INF/spring-configuration-metadata.json with an annotation processor, and editors read it from the JARs. The spring_metadata builder writes lib/spring_gen/spring_metadata.json from the same kind of source: the @ConfigurationProperties classes, their /// comments and literal defaults, plus the beans and profiles. It is published with the package, so an editor can read the metadata of an app and of all its dependencies. See Metadata for editors.
Things the build adds that Spring has no counterpart for
Because the generator already reads the configuration at build time, it also writes files Spring has no reason to write:
- typed accessors for theme and message keys (
context.theme.colors.primary), so a renamed key is a compile error: Typed keys; - the Flutter web dev server's
web_dev_config.yaml: The web dev server; - the page loader in
web/index.html: The page loader; - pages for search engines, a sitemap and
llms.txt: Pages for search engines; - the deep link entries of iOS, macOS and Android: Deep links.