Modules left out of the build

A starter can mark one of its auto-configuration modules with build: AutoConfigurationBuild('some.property'). Then the application's configuration decides, when build_runner runs, whether that module is part of the application at all:

The typical user is a feature only developers need, such as the debug panel of spring_boot_starter_flutter. A release build then contains none of its code.

Why

A runtime condition (@ConditionalOnProperty) switches beans off when the application starts. The code of those beans is still compiled into the app: their classes, their widgets, their strings. For a debug panel that is dead weight in every release, and it shows users and reverse engineers what the panel can do.

A build condition works one step earlier. It decides whether the module's code is referenced by the generated application at all. Code that nothing references is removed by the Dart compiler (tree shaking), so a module left out costs nothing in the shipped app.

Three goals shaped the design:

Declaring a module (starter authors)

The annotation goes on the module variable in the starter's lib/spring_auto_configuration.dart, like any auto-configuration module (see Auto-configurations):

// lib/spring_auto_configuration.dart of the package `neon_inspector`
import 'package:spring_boot_dart/spring_boot_dart.dart';
import 'spring_gen/src/inspector.spring.dart';

// The module every application gets.
@AutoConfigurationModule()
final BeanModule neonInspectorAutoConfiguration = $neonInspectorBeans;

// The developer tools: by `neon.inspector.enabled`.
// Not set: in debug and profile builds only (the default whenMissing).
@AutoConfigurationModule(
  build: AutoConfigurationBuild('neon.inspector.enabled'),
)
final BeanModule neonInspectorToolsAutoConfiguration = $neonInspectorToolsBeans;

AutoConfigurationBuild has two parameters:

Parameter Type Default Meaning
property (positional) String required The property of the application's configuration that decides.
whenMissing BuildInclusion BuildInclusion.notInRelease Where the module goes when the property is not set.

BuildInclusion has three values:

Value The module is in
BuildInclusion.always every build
BuildInclusion.notInRelease debug and profile builds; a release build compiles it away
BuildInclusion.never no build

A module with build: keeps its order, before and after, and other modules may name it in theirs.

Setting the property (application)

The application sets the property in its own configuration file, in lib/resources/:

# lib/resources/application.yml
neon:
  inspector:
    enabled: false   # no inspector code in any build of this app

or

# lib/resources/application.properties
neon.inspector.enabled=true

Then run dart run build_runner build (or keep watch running). The configuration files of lib/resources/ are inputs of the build, so a change to them makes build_runner write the application's .spring.dart file again.

What the build reads

The build reads the property the way the application reads its configuration, with these limits:

A value set only in a profile's file (application-dev.yml, application-web.properties) is not read; the build warns about it (see Warnings).

The decision

For each module with build:, the generator looks up the property once and decides:

The property is The module is Warning
true always in none
false never in none
not set, or empty as whenMissing says (notInRelease by default) none, unless a profile's file sets it
set only in application-<profile>.* as whenMissing says yes: the build does not read profile files
any other value (yes, 1, off) as whenMissing says yes: not true or false

"Always in" and "never in" are final in the generated code. "Not in a release" is decided by the Dart compiler, from the build mode, as explained below.

What the generated code looks like

The generator writes the @SpringBootApplication output (main.spring.dart, see The application). Its springApplication getter lists the auto-configuration modules. The examples below are real output of example/flutter_guide, only without the import prefixes (_i67.).

true, or whenMissing: always

The module is listed like any other:

SpringApplication get springApplication => SpringApplication(
  [$application],
  autoConfigurations: [
    springBootAutoConfiguration,
    springBootStarterFlutterAutoConfiguration,
    springBootStarterFlutterDebugAutoConfiguration,
    springBootStarterFlutterNavigationAutoConfiguration,
    // ...
  ],
  // ...
);

false, or whenMissing: never

The module is not in the list. Nothing else in the file names it:

SpringApplication get springApplication => SpringApplication(
  [$application],
  autoConfigurations: [
    springBootAutoConfiguration,
    springBootStarterFlutterAutoConfiguration,
    springBootStarterFlutterNavigationAutoConfiguration,
    // ...
  ],
  // ...
);

When nothing else of the starter's spring_auto_configuration.dart is used, the import of that library is gone too. The generator's tests check that the output for false contains no reference to the module, no proxy class of its beans, no source string of them and no import of the starter (library_proxies_test.dart).

Not set, with the default whenMissing: notInRelease

The module is listed under a collection if:

SpringApplication get springApplication => SpringApplication(
  [$application],
  autoConfigurations: [
    springBootAutoConfiguration,
    springBootStarterCacheAutoConfiguration,
    springBootStarterFeignAutoConfiguration,
    springBootStarterFlutterAutoConfiguration,
    if (!const bool.fromEnvironment('dart.vm.product'))
      springBootStarterFlutterDebugAutoConfiguration,
    springBootStarterFlutterNavigationAutoConfiguration,
    // ...
  ],
  // ...
);

When such a module has an order, before or after, its entry in autoConfigurationMetadata is under the same if, so the ordering leaves a release with the module.

What the compiler removes in a release, and why

dart.vm.product is a compile-time environment constant. Flutter sets it to true for flutter build --release and to false for debug and profile builds (Flutter's kReleaseMode is the same constant). dart compile exe sets it to true as well; dart run does not.

When dart.vm.product is true, the compiler sees !const bool.fromEnvironment('dart.vm.product') as the constant false. Step by step:

  1. The condition of the collection if is a constant false, so the element is dropped from the list.
  2. The module variable (springBootStarterFlutterDebugAutoConfiguration) is then referenced from nowhere.
  3. Tree shaking removes what is referenced from nowhere: the variable, its bean definitions, their create closures, and every class, widget and string reachable only through them.
  4. In debug and profile builds the condition is true: the element is in the list and the module works as usual.

This was checked on real builds: a release web build of an app with the debug panel contains none of the panel's strings, and a profile build contains them. The same holds for a small program compiled with dart compile js -Ddart.vm.product=true and dart compile exe: a string reachable only through such an if is not in the output.

What the compiler can remove depends on what else references the code. A class the module uses that the application also uses elsewhere stays, because it is reachable another way.

Proxies of the module's beans

A starter's generated module does not contain the AOP proxy classes of its beans. It leaves them to the application with an AopProxyFactory.deferred placeholder, and the application's build writes the proxy classes its aspects need (see AOP proxies). These proxies follow the build of their module:

The bean is defined by Its proxy in the application
only modules decided never not written: no proxy class, no entry in aopProxies, no import of the bean's library
only modules decided notInRelease (or never and notInRelease) registered under the same if, so a release compiles it away
only modules of one platform (see Modules of one platform) registered under that platform's if
at least one module that is always in written as usual

For a bean only in a notInRelease module, the application's module looks like this (from the generator's test, prefixes dropped, the factory's arguments shortened):

BeanModule get $application => BeanModule(
  r'application',
  [
    // the application's beans
  ],
  aopProxies: {
    if (!const bool.fromEnvironment('dart.vm.product'))
      r'package:starter/task.dart#Task': AopProxyFactory(
        signatures: const [/* ... */],
        create: (target, invoker) => _$TaskProxy(target as Task, invoker),
      ),
  },
);

The class _$TaskProxy is referenced only from that entry, so in a release it is removed with it.

Modules of one platform

A module can also be kept to the platform its code works on, with platform: on the same annotation:

// The server half of a starter: only where a server can run.
@AutoConfigurationModule(platform: ModulePlatform.native)
final BeanModule neonInspectorServerAutoConfiguration = $neonInspectorServerBeans;
ModulePlatform The module is in The condition in the generated code
native builds where dart:io exists: the Dart VM, an AOT executable, a Flutter app on a phone or a desktop const bool.fromEnvironment('dart.library.io') || const bool.fromEnvironment('SPRING_ALL_PLATFORMS')
web browser builds, JavaScript or WebAssembly const bool.fromEnvironment('dart.library.js_interop') || const bool.fromEnvironment('SPRING_ALL_PLATFORMS')
server the Dart VM and an AOT executable: dart:io exists and Flutter's dart:ui does not. Never a Flutter app, never a browser (const bool.fromEnvironment('dart.library.io') && !const bool.fromEnvironment('dart.library.ui')) || const bool.fromEnvironment('SPRING_ALL_PLATFORMS')

No property is read: the platform is not the application's choice. The generator lists the module under the constant, and each compiler decides for its own platform. This is real output of example/server_guide, without the import prefixes:

SpringApplication get springApplication => SpringApplication(
  [$application],
  autoConfigurations: [
    springBootAutoConfiguration,
    springBootStarterCacheAutoConfiguration,
    springBootStarterFeignAutoConfiguration,
    springBootStarterLoggingAutoConfiguration,
    springBootStarterOauth2ClientAutoConfiguration,
    springBootStarterSchedulingAutoConfiguration,
    if ((const bool.fromEnvironment('dart.library.io') ||
        const bool.fromEnvironment('SPRING_ALL_PLATFORMS')))
      springBootStarterSecurityAutoConfiguration,
    if ((const bool.fromEnvironment('dart.library.io') ||
        const bool.fromEnvironment('SPRING_ALL_PLATFORMS')))
      springBootStarterSecurityOAuth2ClientAutoConfiguration,
    if ((const bool.fromEnvironment('dart.library.io') ||
        const bool.fromEnvironment('SPRING_ALL_PLATFORMS')))
      springBootStarterWebAutoConfiguration,
    springBootStarterWebsocketAutoConfiguration,
    if ((const bool.fromEnvironment('dart.library.io') ||
        const bool.fromEnvironment('SPRING_ALL_PLATFORMS')))
      springBootStarterWebsocketServerAutoConfiguration,
    springSecurityCoreAutoConfiguration,
  ],
  autoConfigurationMetadata: {
    if ((const bool.fromEnvironment('dart.library.io') ||
        const bool.fromEnvironment('SPRING_ALL_PLATFORMS')))
      springBootStarterSecurityAutoConfiguration:
          const AutoConfigurationModule(
            after: ['springBootStarterOauth2ClientAutoConfiguration'],
          ),
    // ...
  },
  // ...
);

On a server dart.library.io is true and every module is in. Compiled for a browser it is false: the elements are dropped, the module variables are referenced from nowhere, and tree shaking removes them with every class only they reach, as above for a release. So the same generated file serves both platforms, and a Flutter web app whose dependencies bring the web starter carries no server.

A program that runs the server's modules on another platform on purpose, such as the repository's check of server code as minified JavaScript under Node, is compiled with -DSPRING_ALL_PLATFORMS=true: every module stays.

Rules:

Which modules are marked

Every auto-configuration module of the family, by where it is:

Package Module Platform Build property
spring_boot_dart springBootAutoConfiguration every
springBootObservedAnnotationsAutoConfiguration every spring.observations.annotations.enabled (not set: never)
spring_boot_starter_logging springBootStarterLoggingAutoConfiguration every
spring_boot_starter_scheduling springBootStarterSchedulingAutoConfiguration every
spring_boot_starter_cache springBootStarterCacheAutoConfiguration every
springBootStarterCacheStartupChecksAutoConfiguration (cacheOperationValidator) every spring.main.startup-checks.enabled
spring_boot_starter_feign springBootStarterFeignAutoConfiguration every
spring_boot_starter_data springBootStarterDataAutoConfiguration every
springBootStarterDataStartupChecksAutoConfiguration (transactionValidator, dataFailureAnalyzer) every spring.main.startup-checks.enabled
springBootStarterDataSqlLoggingAutoConfiguration (the statement logging, jdbcLogSettings) every spring.data.jdbc.show-sql
spring_boot_starter_oauth2_client springBootStarterOauth2ClientAutoConfiguration every
spring_boot_starter_edge springBootStarterEdgeAutoConfiguration (the fetch server, the runtime) every
springBootStarterEdgeStartupChecksAutoConfiguration (edgeWarnings) every spring.main.startup-checks.enabled
spring_security_core springSecurityCoreAutoConfiguration every
spring_search_dart springSearchDartAutoConfiguration every
spring_boot_starter_websocket springBootStarterWebsocketAutoConfiguration (the clients) every
springBootStarterWebsocketServerAutoConfiguration (the server endpoints) native
spring_boot_starter_supabase springBootStarterSupabaseDataAutoConfiguration (the defaults of the data store) every
springBootStarterSupabaseAutoConfiguration (the beans) every
springBootStarterSupabaseAdminAutoConfiguration (supabaseAuthAdmin) server
springBootStarterSupabaseServerAutoConfiguration (the resource server's defaults) server
spring_boot_starter_web springBootStarterWebAutoConfiguration native
springBootStarterWebRateLimitAutoConfiguration (the rate limiter) native
springBootStarterWebDebugQpsAutoConfiguration native spring.web.debug.qps.enabled (not set: never)
spring_boot_starter_security springBootStarterSecurityAutoConfiguration native
springBootStarterSecurityOAuth2ClientAutoConfiguration native
spring_boot_starter_actuator springBootStarterActuatorAutoConfiguration native
springBootStarterActuatorQpsAutoConfiguration native spring.web.debug.qps.enabled (not set: never)
spring_boot_starter_flutter springBootStarterFlutterAutoConfiguration every
springBootStarterFlutterDebugAutoConfiguration every spring.flutter.debug.enabled
springBootStarterFlutterDebugFrameMeterAutoConfiguration every spring.flutter.debug.frame-meter.enabled
springBootStarterFlutterDebugMotionAutoConfiguration every spring.flutter.debug.motion.enabled
springBootStarterFlutterDebugTimelineAutoConfiguration every spring.flutter.debug.timeline.enabled
springBootStarterFlutterDebugIsolatesAutoConfiguration every spring.flutter.debug.isolates.enabled
springBootStarterFlutterDebugDragAutoConfiguration every spring.flutter.debug.drag.enabled (not set: never)
spring_boot_starter_flutter_scene springBootStarterFlutterSceneAutoConfiguration every spring.flutter.scene.enabled (not set: always)
springBootStarterFlutterSceneDebugAutoConfiguration (the debug panel's scenes tab) every spring.flutter.scene.debug.enabled
spring_boot_starter_flutter_signals springBootStarterFlutterSignalsAutoConfiguration every
springBootStarterFlutterSignalsDebugAutoConfiguration (the debug panel's state tab) every spring.flutter.signals.debug.enabled
spring_boot_starter_flutter_material springBootStarterFlutterMaterialAutoConfiguration every
spring_boot_starter_flutter_cupertino springBootStarterFlutterCupertinoAutoConfiguration every
spring_boot_starter_flutter_navigation springBootStarterFlutterNavigationAutoConfiguration every
spring_boot_starter_flutter_security springBootStarterFlutterSecurityAutoConfiguration every

A build property without a note is "not in a release" when not set. The startup-check modules of the data, cache and edge starters share spring.main.startup-checks.enabled: one key leaves all three out. The data starter's SQL statement logging is its own module, by spring.data.jdbc.show-sql. Each starter's page What a build contains lists its own modules and what the generator writes for it, for example the data starter's.

What is native is what serves: the web server, its security, the actuator's endpoints over it, the server endpoints of WebSocket. server is for code that must not ship in an app, which anyone can read: the admin API of the Supabase starter, which uses the service-role key, and the resource server's defaults. A Flutter app (on a phone, a desktop or the web) has neither. No module of the family is web only. The modules that are everywhere choose their platform-specific parts themselves, with conditional imports: the WebSocket transport, the task executor, the secret store of the Flutter security starter.

A package that is a dependency of a browser app must still compile there. platform: removes the module from the program; it does not excuse a library that cannot be compiled for the browser at all. See WebAssembly.

Parts of the generator by key

A package's part of the generator (see Parts of the packages) can follow a key in the same way: PackageBuild('some.property', whenMissing: ...) is read as AutoConfigurationBuild is. One key can then leave out the package's module and everything the generator writes for it:

No built-in part takes a key yet, and the generated code of the examples did not change with the parts.

What stays in every build

Some code is not switchable on purpose or not yet:

Compiled to JavaScript or WebAssembly

dart compile js and dart compile wasm define no dart.vm.product, so what they compile is not a release build in the sense of notInRelease: an edge function keeps its notInRelease modules (such as the edge starter's warning list) unless the key is false. Flutter's release builds and AOT executables (dart compile exe) drop them.

Warnings

A build condition fails the build only when the build cannot read the property: a ${...} placeholder without a default that only an environment variable or a --dart-define would resolve, or a configuration file that does not parse. The error names the module and the property, and says how to fix it:

neon_inspector.neonInspectorToolsAutoConfiguration: the build reads
neon.inspector.enabled to decide whether the module is built, and could not:
PlaceholderResolutionException: Could not resolve placeholder 'FLAG' in value
"${FLAG}"
Give neon.inspector.enabled a value the build can read in application.yml or
application.properties, or a placeholder with a default (${FLAG:true}):
environment variables and --dart-define values do not exist at build time.

In the other cases it warns, naming the module as <package>.<variable>:

The property is set only in a profile's file.

neon_inspector.neonInspectorToolsAutoConfiguration: neon.inspector.enabled is
set only in application-dev.yml, which the build does not read: it decides by
application.yml or application.properties without a profile. The module is
built as when it is not set.

Move the setting into application.yml or application.properties, or keep it in the profile's file as a runtime switch (see the next section).

The value is not true or false.

neon_inspector.neonInspectorToolsAutoConfiguration: neon.inspector.enabled is
'yes', not true or false; the module is built as when it is not set.

Build conditions and runtime conditions

The two kinds of condition do different jobs and work together:

Build condition (build:) Runtime condition (@ConditionalOnProperty, @Profile, ...)
Decides whether the module's code exists in the app whether the beans are registered when the app starts
Evaluated when build_runner runs, and by the compiler for notInRelease at every start
Reads application.yml / application.properties without outside profiles every property source of the running app: profiles, environment, arguments, --dart-define
Effect on the app's size removes the code none: the code is compiled in
Can turn on what the other turned off no no

So a build condition can remove code, and where the code exists a runtime condition can still switch its beans off. The reverse is impossible: no runtime property can bring back a module the build left out, because its code is not there.

A starter that wants both declares both, as the debug panel does: build: on the module, and a @ConditionalOnProperty with the same property and matchIfMissing: true on its beans.

Worked example: the debug panel

spring_boot_starter_flutter declares its debug panel like this (shortened):

// spring_boot_starter_flutter/lib/spring_auto_configuration.dart

// The panel in a running app: off with spring.flutter.debug.enabled=false
// in a profile, though the build has it.
const _debugOn = ConditionalOnProperty(
  'spring.flutter.debug.enabled',
  havingValue: 'true',
  matchIfMissing: true,
);

@AutoConfigurationModule(
  build: AutoConfigurationBuild('spring.flutter.debug.enabled'),
)
final BeanModule springBootStarterFlutterDebugAutoConfiguration = BeanModule(
  'springBootStarterFlutterDebugAutoConfiguration',
  [
    BeanDefinition<DebugPanel>(
      name: 'debugPanel',
      conditions: const [_debugOn],
      create: (_) => DebugPanel(),
      // ...
    ),
    // the sections: logs, frames, configuration, beans, theme, start;
    // and debugPanelCustomizer, which puts the panel over the app
  ],
);

What an app gets, by the value of spring.flutter.debug.enabled in application.yml (or application.properties):

spring.flutter.debug.enabled Debug and profile builds Release build
not set the panel's code is in; the panel is on, unless the running app reads false (a profile's file, an argument) no code
true the code is in; the panel is on, unless the running app reads false the code is in; the panel is on, unless the running app reads false
false no code no code

Most apps set nothing: developers get the panel, users never ship it. Set true to keep it in a release build (an internal test build), and false to have it in no build at all.

Cost on build time

Build conditions add almost nothing to a build, and nothing at all to an application whose starters use none:

What is tested

The generator's tests build applications against a fake starter and check the generated code:

See also