spring_core_dart_generator

spring_core_dart_generator is the code generator of Spring for Dart. It reads the annotations of your code (@Service, @Value, @Bean, @Aspect, @RestController, ...) when you run build_runner, and writes plain Dart code that creates your objects and connects them. You never call it from your code. You add it as a dev dependency and run build_runner.

Every application that uses spring_core_dart, spring_boot_dart or one of the starters needs it. Without the generated code the annotations do nothing: they are only constant objects that nobody reads.

Why

Spring (Java) finds annotated classes when the application starts. It scans the classpath, reads the annotations with reflection and creates the beans with reflection.

Dart cannot do this in most places it runs:

So the work moves to build time. build_runner gives the generator the analyzer's full view of your code: every class, constructor, parameter type and annotation value. The generator answers the questions Spring answers at startup (which classes are beans, what each constructor needs, which methods are event listeners, which beans an aspect may advise) and writes the answers down as Dart code:

This code runs on every platform, survives minification, and lets the compiler remove what nothing uses. It also lets the build report many mistakes (a misplaced annotation, a bad pointcut, a private bean type) before the application ever runs.

Installation

# pubspec.yaml
dependencies:
  spring_boot_dart: ^0.9.0            # or a starter, such as spring_boot_starter_web

dev_dependencies:
  build_runner: ^2.17.0
  spring_core_dart_generator: ^0.9.0  # required: it writes the bean definitions

Nothing else is needed. The generator's builders apply themselves to every package that depends on it (auto_apply: dependents in its build.yaml), so there is no build.yaml to write in your package unless you want to change an option.

The generator does not depend on spring_boot_dart or the starters. It recognises their annotations by name and library URL, so you can use it with spring_core_dart alone.

First run

dart run build_runner build   # generate once
dart run build_runner watch   # generate again on every save

Run build after you add, remove or change annotations, beans or files of lib/resources/. During development, watch keeps the generated files up to date while you type. On watch, a file with a syntax error does not delete the generated code: the last good version stays until the sources parse again (see How the generation works).

If build_runner reports conflicting outputs from another generator, add --delete-conflicting-outputs.

The files that appear

Generated files go into a spring_gen/ folder at the top of the source root they belong to, and mirror the rest of the path:

my_app/
  bin/
    main.dart                    # yours: @SpringBootApplication() on main
    spring_gen/
      main.spring.dart           # generated: the whole application
  lib/
    src/
      beans.dart                 # yours: a @ComponentScan() variable
    spring_gen/
      src/
        beans.spring.dart        # generated: the beans of lib/src/
      spring_metadata.json       # generated: properties and beans, for editors
  test/
    shop_test.dart               # yours: @SpringBootTest classes
    spring_gen/
      shop.test.spring.dart      # generated: runSpringTests()

Only a few of your files get a generated file:

Your file Generated file Page
a library with @SpringBootApplication() on main <root>/spring_gen/<path>.spring.dart with the whole application @SpringBootApplication
a library with a @ComponentScan() variable <root>/spring_gen/<path>.spring.dart with one BeanModule @ComponentScan modules
test/<name>_test.dart with @SpringBootTest or @DataTest classes test/spring_gen/<name>.test.spring.dart Tests
a package with Spring code lib/spring_gen/spring_metadata.json Metadata for editors

Every other Dart file is skipped after a quick text check. Flutter apps get a few more files (typed theme and message keys, the page loader in web/index.html, and others); see The builders.

Commit the generated files with the rest of your code. They are part of the program: main.dart imports main.spring.dart, and a published package ships its generated modules and its spring_metadata.json.

A complete example

One file is enough for a command-line application:

// bin/main.dart
import 'package:spring_boot_dart/spring_boot_dart.dart';

import 'spring_gen/main.spring.dart'; // written by the generator

@Component()
class Greeter {
  // A setting, with its default after the colon.
  Greeter(@Value(r'${greeting.punctuation:!}') this.punctuation);

  final String punctuation;

  String greet(String name) => 'Hello, $name$punctuation';
}

@Component()
class Hello implements CommandLineRunner {
  Hello(this.greeter);

  final Greeter greeter;

  @override
  void run(List<String> args) => print(greeter.greet('Ada'));
}

@SpringBootApplication()
void main(List<String> args) => runApplication(args);

dart run build_runner build writes bin/spring_gen/main.spring.dart. Simplified (the real file imports each library with a prefix such as _i1., writes an aopProxy: argument per bean and lists more --dart-define keys):

// GENERATED CODE - DO NOT MODIFY BY HAND
// Generated by spring_core_dart_generator from @ComponentScan.

/// Beans found by `@ComponentScan` in `lib/ and bin/`.
BeanModule get $application => BeanModule(r'application', [
  BeanDefinition<Greeter>(
    name: r'greeter',
    source: r'asset:my_app/bin/main.dart#Greeter',
    dependencies: const [Dependency.value(r'${greeting.punctuation:!}')],
    create: (r) => Greeter(r.value<String>(r'${greeting.punctuation:!}')),
    annotations: const [Component()],
  ),
  BeanDefinition<Hello>(
    name: r'hello',
    source: r'asset:my_app/bin/main.dart#Hello',
    types: const [Hello, CommandLineRunner],
    dependencies: const [Dependency(Greeter, name: r'greeter')],
    create: (r) => Hello(r.dependency<Greeter>(name: r'greeter')),
    annotations: const [Component()],
  ),
]);

/// The `@SpringBootApplication` of the current code (a getter, so it is
/// up to date after a hot reload).
SpringApplication get springApplication => SpringApplication(
  [$application],
  autoConfigurations: [springBootAutoConfiguration],
  dartDefines: {
    if (const bool.hasEnvironment('GREETING_PUNCTUATION'))
      'GREETING_PUNCTUATION': const String.fromEnvironment('GREETING_PUNCTUATION'),
    if (const bool.hasEnvironment('greeting.punctuation'))
      'greeting.punctuation': const String.fromEnvironment('greeting.punctuation'),
    // ... and the keys every application may read (SPRING_PROFILES_ACTIVE, ...)
  },
  fingerprint: !const bool.fromEnvironment('dart.vm.product')
      ? _$fingerprint
      : null,
);

ConfigurableApplicationContext runApplication(List<String> args) =>
    springApplication.run(args, hotReload: () => springApplication);

// runApplicationAsync ...

// main.spring.debug.dart: a part, compiled in debug and profile builds only
const _$fingerprint = '3ada566f';
// reloadApplication, reloadApplicationAsync ...

What to notice:

Run it:

dart run bin/main.dart                           # Hello, Ada!
dart run bin/main.dart '--greeting.punctuation=?' # Hello, Ada?

A library without @SpringBootApplication uses a @ComponentScan() variable instead, and passes the module to a context itself:

// lib/src/beans.dart
import 'package:spring_core_dart/spring_core_dart.dart';
import 'package:my_app/spring_gen/src/beans.spring.dart'; // written by the generator

@ComponentScan()
final BeanModule appBeans = $appBeans;

// elsewhere
final context = ApplicationContext.run([appBeans]);

Where to go next

Getting started:

Generated code:

More:

In Spring (Java)

// Classic Spring discovers beans when the context starts:
// ClassPathBeanDefinitionScanner reads class files, and reflection
// creates the instances.
var context = new AnnotationConfigApplicationContext();
context.scan("com.example.app");
context.refresh();

The closest Spring feature is Spring 6 AOT (BeanFactoryInitializationAotProcessor), which can write Java source for the bean definitions at build time for GraalVM native images. In Spring for Dart this is not an option: it is the only way, on every platform.

See also