Your own starter

Any package can be a starter. An application adds it to pubspec.yaml, runs build_runner again, and gets its beans with no code of its own. This is how every starter of Spring for Dart works, from logging to the web server, and nothing in them is special: a starter of yours is found the same way.

Why

Some code repeats from application to application: a client for your company's API, an audit log, a mail sender, metrics. Copying it means copying its wiring too: which beans to create, which settings they read, what to do when an application needs something different. A starter packages the code and its wiring once:

How a starter is found

When the generator builds an application with @SpringBootApplication, it walks every package of the application's dependencies, direct and transitive. In each package it reads lib/spring_auto_configuration.dart, if there is one, and lists every top-level BeanModule variable marked @AutoConfigurationModule in the generated springApplication:

// bin/spring_gen/main.spring.dart of the application (generated)
SpringApplication get springApplication => SpringApplication(
  [$application],
  autoConfigurations: [
    neonAuditAutoConfiguration,   // found in neon_audit
    springBootAutoConfiguration,  // spring_boot_dart
    // ... every other starter
  ],
);

There is no list to maintain and no annotation to add in the application. Discovery happens at build time, so after adding a starter the application runs build_runner once more. How the modules are sorted and checked is on Auto-configurations.

A complete starter

The example is neon_audit: it records what the application does through an AuditSink, writes to the log by default, and is configured under neon.audit.*.

1. The package

# pubspec.yaml of neon_audit
name: neon_audit
environment:
  sdk: ^3.13.0

dependencies:
  spring_boot_dart: ^0.9.0

dev_dependencies:
  build_runner: ^2.17.0
  spring_core_dart_generator: ^0.9.0
  spring_boot_starter_test: ^0.9.0
  test: ^1.33.0

2. The beans and their conditions

The beans are declared as in an application: an @AutoConfiguration class (a @Configuration for starters) with @Bean methods. Conditions decide when each bean is created.

// lib/src/audit.dart
import 'package:spring_boot_dart/spring_boot_dart.dart';

/// Where audit records go.
abstract interface class AuditSink {
  void record(String event);
}

/// The default sink: the application's log.
class LogAuditSink implements AuditSink {
  LogAuditSink(this.prefix);

  final String prefix;

  @override
  void record(String event) => const SpringLog('neon.audit').info('$prefix$event');
}

@AutoConfiguration()
class AuditAutoConfiguration {
  @Bean()
  // The application's own AuditSink wins: this one is created only
  // when there is none.
  @ConditionalOnMissingBean(AuditSink)
  // `neon.audit.enabled=false` switches the starter off.
  @ConditionalOnProperty('neon.audit.enabled', matchIfMissing: true)
  AuditSink auditSink(AuditProperties properties) =>
      LogAuditSink(properties.prefix);
}

@ConditionalOnMissingBean is what makes a starter replaceable. The application's beans are registered before every auto-configuration, so the condition sees them: an application that declares its own AuditSink gets only its own.

3. Typed properties

// lib/src/audit_properties.dart
import 'package:spring_boot_dart/spring_boot_dart.dart';

/// The `neon.audit.*` properties.
@ConfigurationProperties('neon.audit')
class AuditProperties {
  /// Whether the starter records anything.
  bool enabled = true;

  /// Put before every record.
  String prefix = 'audit: ';
}

The /// comments and the initial values are not only for readers. The generator writes them into lib/spring_gen/spring_metadata.json, which is published with the package, so an editor completes neon.audit.prefix in an application's application.yml and shows its description and default. See Metadata for editors.

4. The module

A @ComponentScan collects the beans of its folder into a module, and lib/spring_auto_configuration.dart declares that module as the starter's auto-configuration. The file name is fixed: it is where the generator looks.

// lib/src/beans.dart
import 'package:spring_boot_dart/spring_boot_dart.dart';
import 'package:neon_audit/spring_gen/src/beans.spring.dart';

@ComponentScan()
final BeanModule auditBeans = $auditBeans;
// lib/spring_auto_configuration.dart
import 'package:spring_boot_dart/spring_boot_dart.dart';
import 'package:neon_audit/src/beans.dart';

// requires: the spring_boot_dart versions the starter works with.
@AutoConfigurationModule(requires: '^0.7.0')
final BeanModule neonAuditAutoConfiguration = auditBeans;

requires is checked when an application is built: with a spring_boot_dart outside the range, the build stops and names the version to use. The other options of @AutoConfigurationModule:

Option What it does
requires the compatible spring_boot_dart versions, a pub version range; null accepts any
order, before, after where the module goes among the others, when its beans depend on another starter's
build leaves the module out of the build, or out of a release, by a property of the application: for development tools such as a debug panel. See Modules left out of the build
platform keeps the module to where its code works: ModulePlatform.native (where dart:io exists, so not a browser), ModulePlatform.web, or ModulePlatform.server (the Dart VM and AOT executables only, never a Flutter app: for code that must not ship in an app, such as an API that needs a secret key). Another platform's build has none of it. Put the server half of a starter in a module of its own with native, so a browser app that uses the client half carries no server. See Modules of one platform
factories constants the application finds by type before any bean exists. See Factories

The repository's own starters write their BeanDefinitions by hand for full control. Both ways give the same kind of module; the generator is the shorter one.

5. Generate and publish

The generator writes files only into the package being built, never into a dependency. So the starter generates its own code and publishes it:

dart run build_runner build
dart pub publish

Commit and publish the lib/spring_gen/ files with the package. Applications never run the generator over a dependency's lib/.

Using it

The application adds the dependency and builds:

dependencies:
  neon_audit: ^1.0.0
@Service()
class Checkout {
  Checkout(this.audit);

  final AuditSink audit;   // the starter's bean, injected like any other

  void pay(String order) => audit.record('paid $order');
}
# lib/resources/application.yml
neon:
  audit:
    prefix: 'shop: '

And to replace the default, the application declares its own bean; the starter's backs off:

@Component()
class DatabaseAuditSink implements AuditSink {
  @override
  void record(String event) { /* ... */ }
}

Testing a starter

ApplicationContextRunner from spring_boot_starter_test starts a small context per test with only the modules and properties you give it. Test the three cases every starter has: the default, the back-off and the switch.

import 'package:neon_audit/spring_auto_configuration.dart';
import 'package:neon_audit/src/audit.dart';
import 'package:spring_boot_starter_test/spring_boot_starter_test.dart';
import 'package:test/test.dart';

class MemoryAuditSink implements AuditSink {
  @override
  void record(String event) {}
}

void main() {
  final runner = const ApplicationContextRunner()
      .withAutoConfiguration(neonAuditAutoConfiguration);

  test('a log sink by default', () {
    runner.run((context) {
      expect(context, hasSingleBean<AuditSink>());
      expect(context.getBean<AuditSink>(), isA<LogAuditSink>());
    });
  });

  test("the application's sink wins", () {
    runner.withBean<AuditSink>(MemoryAuditSink.new).run((context) {
      expect(context, hasSingleBean<AuditSink>());
      expect(context.getBean<AuditSink>(), isA<MemoryAuditSink>());
    });
  });

  test('neon.audit.enabled=false switches it off', () {
    runner.withPropertyValues(['neon.audit.enabled=false']).run((context) {
      expect(context, doesNotHaveBean<AuditSink>());
    });
  });
}

The runner reads no config files, binds @ConfigurationProperties as an application does, and every with... call returns a new runner, so a base runner is shared between tests.

Factories: what works before the beans

The beans of a starter exist once the context is created. Some things must work earlier: while the environment is prepared, or while a Flutter app shows its splash. The design library a Flutter theme is read with is one of them. The theme of the splash is read before any bean exists, so a design starter cannot give its design as a bean.

Such things are factories: constants the starter lists on its module.

// lib/spring_auto_configuration.dart of ocean_design
import 'package:ocean_design/src/beans.dart';
import 'package:ocean_design/src/ocean_theme_design.dart';
import 'package:spring_boot_dart/spring_boot_dart.dart';

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

The code that needs them asks the application for a type. SpringApplication.factories.load<T>() gives every factory of type T of the application's modules: by Ordered where they implement it, else in the order of the modules, and an empty list when no starter has one.

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

Once the context exists, it has the same object as the springFactories bean (SpringFactories), so beans can read the factories too.

Each factory must be a public constant, because the generator writes it into the application's generated springApplication:

Form Example
a const constructor call with literal arguments OceanThemeDesign(), OceanThemeDesign(contrast: 0.5)
the same with a named constructor OceanThemeDesign.dark()
a top-level const variable oceanThemeDesign
a static const field OceanThemeDesign.standard

A factory in any other form, a private class or constant for example, stops the build with an explanation. An application gets the factories of a starter when it is generated: after adding a starter that has some, or a version that added some, run build_runner again.

Keep factories for what must exist before the beans. Everything else stays a bean: an application can replace a bean with its own, not a factory.

In Spring (Java), a starter lists such classes in META-INF/spring.factories, and Spring finds them on the class path:

# META-INF/spring.factories
com.neon.ocean.ThemeDesign=com.neon.ocean.OceanThemeDesign
List<ThemeDesign> designs =
    SpringFactoriesLoader.loadFactories(ThemeDesign.class, classLoader);

Dart has no class path to scan, so the generator copies the constants into the application. See Factories and Auto-configurations.

Good to know