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:

What it costs:

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:

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:

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:

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: