
# 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:

- Flutter, AOT executables (`dart compile exe`) and the web have no `dart:mirrors`, so a program cannot list its classes or read their annotations at run time.
- Even where `dart:mirrors` exists (the Dart VM in JIT mode), a program that uses it cannot have its unused code removed by tree shaking, since any class may be looked up by name.

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:

- a constructor call per bean, instead of reflective instantiation;
- a closure per injected field or setter, instead of reflective field access;
- a generated proxy class per advised bean, instead of a runtime proxy;
- constants for the annotations, the property names and the files of `lib/resources/`.

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

```yaml
# 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

```bash
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](how-it-works.md)).

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:

```text
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](spring-boot-application.md) |
| a library with a `@ComponentScan()` variable | `<root>/spring_gen/<path>.spring.dart` with one `BeanModule` | [@ComponentScan modules](component-scan.md) |
| `test/<name>_test.dart` with `@SpringBootTest` or `@DataTest` classes | `test/spring_gen/<name>.test.spring.dart` | [Tests](tests.md) |
| a package with Spring code | `lib/spring_gen/spring_metadata.json` | [Metadata for editors](metadata.md) |

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](builders.md).

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:

```dart
// 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):

```dart
// 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:

- **Each bean is a constructor call.** `create` receives a resolver `r` and asks it for each argument: a bean by type and parameter name, or a resolved property value. No reflection is involved.
- **`dependencies` lists what `create` will ask for.** The container reads it to find missing beans and cycles before it creates anything.
- **`types` lists the types the bean is found under.** It is left out when it is only the class itself, the runtime default; `Hello` also implements `CommandLineRunner`, so it is listed.
- **The application is complete.** `springApplication` holds the beans, the auto-configuration of every starter in your dependencies, and the `--dart-define` keys the program may read. `runApplication` starts it.

Run it:

```bash
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:

```dart
// 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:

- [How the generation works](how-it-works.md): build_runner, the order of the builders, what is resolved, and what happens on `watch`.
- [The builders](builders.md): every builder of the package, what it writes and how to turn one off.

Generated code:

- [@ComponentScan modules](component-scan.md): one module per directory, nested scans, filters.
- [The application: @SpringBootApplication](spring-boot-application.md): the whole package, `runApplication` and hot reload.
- [Bean definitions](bean-definitions.md): how each annotation becomes part of a `BeanDefinition`.
- [Auto-configurations](auto-configurations.md): the starters' modules in your application.
- [Embedded resources](resources.md): the files of `lib/resources/` on every platform.
- [--dart-define keys](dart-defines.md): build-time values for Flutter, the web and AOT.
- [@Log](log.md): the `log` getter.
- [Tests](tests.md): `@SpringBootTest` and `@DataTest`.
- [Data](data.md): entities, repositories and queries.

More:

- [Optimizations](optimizations/index.md): only the code that runs is generated.
- [Flutter](flutter/index.md): typed keys, the web dev server, the page loader, search engines, deep links.
- [Build-time checks](checks.md) and [Errors and the generated files](errors.md).
- [Options](options.md), [Properties the build reads](build-properties.md), [Metadata for editors](metadata.md), [Differences from Spring](differences.md).

## In Spring (Java)

```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

- [spring_core_dart](../spring-core-dart/index.md): the annotations the generator reads.
- [BeanModule](../spring-core-dart/beans/bean-module.md): what a generated module is at run time.
- [@ComponentScan](../spring-core-dart/beans/component-scan.md): the annotation itself.
