
# Spring for Dart

The Spring for Dart extension gives Zed the editor support that IntelliJ IDEA gives Spring in Java. It is for applications built with `spring_core_dart`, `spring_boot_dart` and the `spring_boot_starter_*` packages.

In such an application much of the wiring lives in annotations and strings: which bean a constructor parameter gets, which property `${shop.name}` reads, what a SpEL expression or a pointcut means. The Dart analyzer sees none of that. The extension adds a second language server, `dart_spring`, that does. It runs next to the Dart language server, and its results are added to the Dart server's.

| | |
|---|---|
| Extension id | `dart-spring` |
| Version | `0.7.1`, always the version of the framework it supports |
| Languages | Dart, YAML, Properties |
| Source | [extensions/zed/dart_spring](https://github.com/farum-azula/spring_core_dart/tree/main/extensions/zed/dart_spring) in the spring_core_dart repository |
| Language server | [extensions/language_server](https://github.com/farum-azula/spring_core_dart/tree/main/extensions/language_server) |

The extension lives in the framework's repository, not in the repository of the other Zed extensions. See [Installation](installation.md#spring-for-dart).

## What it gives

- **Navigation.** Go to Definition (`F12` or `Cmd`-click) from an injection point to its beans, from `${key}` to the property, from a pointcut to the class, from a route path to its screen.
- **Hovers.** The value of a property in every profile file, the candidate beans of an injection point, the file a `resources:` location resolves to, the expression of a named pointcut.
- **Checks while you type.** Invalid SpEL, invalid pointcuts, unknown properties, a placeholder in a normal string, missing assets, unknown config keys, ambiguous beans.
- **Highlighting** of SpEL, placeholders, pointcuts and `@Query` SQL inside Dart strings, and of placeholders in config files.
- **Completion, hovers and checks in config files** from the Spring metadata of your package and its dependencies.
- **Spring Data support** inside `@Query('...')` and derived query names.
- **Snippets** for Dart, and for themes in YAML and `.properties` files.
- **The Properties language** for `.properties` files.
- **A project generator**, `dart_spring_lsp create`, like Spring Initializr.

## Navigation

Go to Definition puts the cursor at the target without selecting it.

| Click on | Goes to |
|---|---|
| The type of an injection point: a constructor parameter, a field, an `@Autowired` setter or method, a `@Bean` method parameter | Every bean of that type, `@Primary` first. `List<T>`, `Set<T>` and `ObjectProvider<T>` go to the beans of `T` |
| `this.payments` in a bean constructor | The beans of the field's type |
| A parameter or field with `@Qualifier('cash')`, or the `'cash'` string itself | The bean named or qualified `cash` |
| `@DependsOn`, `@ConditionalOnBean`, `@ConditionalOnMissingBean.named` strings | Those beans |
| `getBean<Clock>()`, `getBeanProvider<T>()`, `context.bean<T>()` | The beans of that type |
| `context.basket`, a getter generated for a `@BuildContextAccess` bean | That bean |
| A type in the bean record of a widget: `SpringStatelessWidget<(Basket, {Clock utc})>`, `SpringStatefulWidget<...>`, `SpringState<W, (...)>` | The beans of that type; a named field picks by its name |
| `${shop.name}` in `@Value`, `getProperty('shop.name')`, `@ConditionalOnProperty` | The key in every `application*.properties` that defines it |
| `@ConfigurationProperties('shop')` | The `shop.*` keys |
| A bean name in SpEL: `#{appConfig.name}`, `#{@clock.now()}` | That bean |
| `resources:legacy.properties` (in `@PropertySource`, `@Value`, `getResource`), `file:config/app.properties`, `asset:assets/logo.png` | The file. `resources:` is `lib/resources/` of the package (`test/resources/` first in tests); `file:` and `asset:` are relative to the package |
| A type in a pointcut: `within(...)`, `execution(...)`, `@annotation(Timed)` | The class; wildcards like `*Service` give every match |
| `pricing()`, `AuditAspect.pricing()` in a pointcut | The `@Pointcut` method |
| `bean(order*)`, the method of `execution(* OrderService.place*(..))` | The matching beans and methods |
| `#isbn` in a cache key or condition: `@Cacheable('books', key: '#isbn')` | The method parameter |
| A screen path: `context.route.go('/catalog/books/978-0')`, `push`, `RouteLocation.parse` / `expand`, a branch of `@RouteShell(branches: [...])` or `@ScreenRoute(branch: '/more')`, `@RouteInfo(paths: [...])`, `spring.flutter.navigation.initial` / `login` / `redirects` in a config file | The `@ScreenRoute` class (or `ScreenRoutes` screen) whose pattern matches, path variables and `{*rest}` included. A branch no shell has is underlined |
| `#{nav.catalog}` in `@ScreenRoute(title:)`, `@RouteInfo(description:)` or `ScreenRoutes...screen(title:)` | The key in `messages*.properties`. The hover shows the message, keys are completed after `#{`, and an unknown key is a warning |

## Hovers

A hover on an injection point lists the candidate beans with the file each one is declared in. For this constructor:

```dart
@Service()
class Checkout {
  Checkout(this.payments, @Value(r'${shop.name}') this.shopName);

  final PaymentService payments;
  final String shopName;
}
```

hovering `PaymentService` shows:

```text
Beans of type PaymentService

- bean 'cardPayments': CardPayments @Primary — lib/src/card_payments.dart
- bean 'cashPayments': CashPayments @Profile([dev]) — lib/src/cash_payments.dart
```

Hovering `shop.name` in the placeholder shows its value in each file that sets it:

```text
shop.name

- application.properties: Book Shop
- application-dev.properties: Book Shop (dev)
```

When nothing is found, the hover says so: `PaymentService: no bean found in this project`, or `shop.name: not defined in any properties file; the default after the colon is used: Shop`. For a `resources:` location that does not exist, it lists the folders it looked in.

## Checks while you type

Problems appear as underlines in the editor and in the diagnostics panel.

- **Invalid SpEL** (`#{1 +}`): an error at the position the parser reports. SpEL is parsed by `spring_core_dart` itself, so the editor rejects exactly what the runtime would.
- **Invalid pointcuts**, checked by the runtime's own parser with the project's `@Pointcut` methods: an unknown `ordrs()` is underlined.
- **Cache keys and conditions** (`key:`, `condition:`, `unless:` of `@Cacheable`, `@CachePut` and `@CacheEvict`, also inside `@Caching`): the SpEL syntax, and a `#isbm` that is not a parameter (nor `#root`, `#result`, `#p0`) is a warning that lists the parameters.
- **An undefined placeholder**: a `${key}` without a default that no properties file and no property of the metadata defines is a warning.
- **A placeholder in a normal string**: `@Value('${key}')` is an error, because in Dart that is string interpolation. The message reads: `In Dart ${...} in a normal string is interpolation, not a placeholder: use a raw string, r'${key}' (or escape: '\${key}')`.
- **Test containers** (`spring_boot_starter_test/containers.dart`): a `@Container` field that is not `static`, and `@ServiceConnection` on a `GenericContainer`, are errors. The properties of a `@ServiceConnection` `PostgresContainer` or `KeycloakContainer` count as defined in that test file, and their hover says which container provides them.
- **Flutter assets**: `@Value('asset:...')` with a missing file, or one not declared under `flutter: assets:` in `pubspec.yaml`, is a warning with the entry to add.
- **Injection points**: no bean is an error; several beans and none `@Primary` is a warning that says which profiles were considered.
- **Profiles**: `@Profile('x')` with a profile that no `application-x` file or metadata knows is a warning, with "Did you mean" when a known profile is close.

## Highlighting inside strings

With semantic highlighting on (see [Configuration](#configuration)), the extension colours the inside of annotation strings:

- **SpEL and placeholders**: keywords, operators, numbers, strings, `#variables`, `@beans`, methods, properties, `T(Types)` and placeholder keys. Also in `@Scheduled` cron and interval strings, and in plain-SpEL cache keys.
- **Pointcuts**: the designators (`execution`, `within`, `@annotation`, ...), `&&`, `||`, `!`, types, annotations, bean patterns, method names and named pointcuts.
- **SQL in `@Query`**: see [Spring Data repositories](#spring-data-repositories).
- **A closure's parameters** get a token of their own, `closureParameter`, where they are declared and everywhere the closure's body uses them, as in `(alert) => heard.add('${alert.isbn}')`. A name declared again inside the closure hides it. Parameters of functions and methods are left as they are.

In config files, `${key}`, `${key:default}` and `#{...}` in the values of `application*.yml` / `.yaml`, of YAML under `resources/` and of `.properties` files are highlighted the same way. In YAML, SpEL counts only in quotes, as YAML reads an unquoted `#` as a comment.

## Config files and the Spring metadata

The generator writes `lib/spring_gen/spring_metadata.json` for every package with Spring code. The language server reads that file for your package and for all its dependencies (found through `.dart_tool/package_config.json`), and reloads it when a build changes it. In `application*.yml`, `.properties` files and YAML under `lib/resources/`, it gives:

- **Completion** of keys, aware of nested YAML (the keys below the ones above the cursor, dotted keys, list and map patterns), and of values: the enum hints of the metadata, `true` / `false`, the profiles for `spring.profiles.active`, `$colors.<role>` and the declared colors and tokens (`$neon.cyan`) in a theme, and the parts of a color object (`color`, `alpha`, `mix`).
- **Hovers** with the description, type, default, and the class and file that declare the key; the values and range of a hint; for a theme key, the Flutter field it sets and whether it takes a value per state.
- **Checks**: an unknown key with "Did you mean", a wrong type (`port: abc`), a number out of range, a value the metadata warns about (a port browsers refuse), theme keys and colors, and a broken `$` reference.
- **Loaders and the splash** (`loaders.<name>`, `splash`): the `kind` values, the built-in ones and the `@ThemeLoaderKind` classes of the workspace; the keys each kind takes; `splash.loader` and `splash.animation` checked and completed from the declared names; the `web:` file of a loader checked and completed from the `.html` files.
- **Go to definition** of a `$` reference to where it is declared, also in a dependency's theme; of `splash.loader: name` to `loaders.<name>`; of `web:` to the file; and of a `${key}` to every profile file that sets it.
- **SpEL beans** in config values and Dart strings: `#{@bean.member}` completes beans after `@` and members after `.`, shows the type on hover, goes to the bean, and reports an unknown bean or member.

An unknown key looks like this in the diagnostics panel:

```text
Unknown property 'prot' in 'server'. Did you mean 'port'?
```

Unsaved keys of an open config file count for navigation and the unknown-key check.

A package without a metadata file shows one information line at the top of its files: `No Spring metadata for my_app: run build_runner (dart run build_runner build) to get completion, hovers and checks for keys, beans and the theme`. Until then the editor does not guess: keys that dependencies may define are not reported as unknown.

## Spring Data repositories

For `spring_boot_starter_data`, inside the `@Query('...')` of a repository method (adjacent string literals count as one text) and in derived query names such as `findByTitle`:

- **Highlighting** of the SQL: keywords, table and column names, aliases, numbers, strings, comments, `:params`, `{Entity.property}` and `:#{...}` SpEL.
- **Go to definition**: `{Book}` to the entity class, `{Book.author}` to the field, `:year` and `#year` to the method parameter, a bean in SpEL to the bean, the property part of a derived name (`findByTitle`) to the field.
- **Hovers**: the entity with its table, id and properties; a property with its column, type and reference; a parameter with its type; and for a derived query name, the SQL it stands for.
- **Completion** after `{` (entities), `{Book.` (stored properties), `:` (the method's parameters), and the parameters, beans and members inside `:#{`.
- **Checks**: an unknown `{Entity}` or `{Entity.property}` with "Did you mean", a `:name` that is not a parameter (error), a parameter the query never uses (warning; `Pageable` and `Sort` excepted), invalid SpEL in `:#{...}`, a plain `?`, unbalanced quotes, parentheses and braces. In a derived name: an unknown property, a collection or nested path, and a parameter count that does not fit the name.

A table or column the database has but no entity declares is not checked. See [Queries](../../components/spring-boot-starter-data/query.md) and [Derived queries](../../components/spring-boot-starter-data/derived-queries.md).

## The Properties language

The extension brings a Properties language for `.properties` files, built on tree-sitter-properties at the same commit Zed's Java extension uses, so both highlight the same way. It colours keys, values, `#` and `!` comments, escapes, `\` line continuations, Spring's `${key}` and `${key:default}` placeholders (environment variables like `${PORT:8080}` in another colour) and list indexes (`servers[0].host`). `Cmd-/` comments lines out.

## Snippets

Type the prefix and press `Tab`. Fields are filled in order with `Tab`; a field that appears twice is edited in both places at once.

For example, `spservice` expands to:

```dart
@Service()
class NameService {
  NameService(this.repository);

  final Repository repository;

}
```

with `Name` selected first, then `repository`, then `Repository`. `spvalue` expands to:

```dart
@Value(r'${app.key:default}')
late final String name;
```

### Dart

| Prefix | Inserts |
|---|---|
| `spboot` | `main` with `@SpringBootApplication` |
| `spscan` | A `@ComponentScan` module (`spring_core_dart` without Boot) |
| `spservice`, `spcomponent`, `sprepository` | A bean class |
| `spiface` | An interface and its `@Service` implementation |
| `spconfig`, `spbean` | A `@Configuration` class, a `@Bean` method |
| `spvalue`, `spvalueparam` | A field or constructor parameter filled from a property |
| `spautowired`, `spsetter` | Field or setter injection |
| `spqualifier`, `spprimary`, `spprofile` | Choosing between beans |
| `spself` | `@Lazy` self-injection, so advice applies to self-calls |
| `sppost`, `sppre` | `@PostConstruct`, `@PreDestroy` |
| `splistener`, `sppublish` | An `@EventListener`, publishing an event |
| `spaspect` | An annotation and an `@Around` aspect for it |
| `spprops`, `spcondprop`, `sprunner` | `@ConfigurationProperties`, `@ConditionalOnProperty`, a `CommandLineRunner` |
| `splog`, `splogger` | `@Log` (a generated `log` getter), a `SpringLog` constant |
| `sptest` | A test file with `springBootTest` and a `BeanOverride` |

### Flutter

For `spring_boot_starter_flutter`:

| Prefix | Inserts |
|---|---|
| `spflutter` | `main` with `@SpringBootApplication` under `SpringApplicationWidget` |
| `spstateless`, `spstateful` | A `SpringStatelessWidget<(...)>`, a `SpringStatefulWidget` with its `SpringState`, reading `beans` |
| `spnotifier` | A `@ChangeNotifierComponent` with `@BuildContextAccess` |
| `spaccess`, `spnotify` | `@BuildContextAccess(name: ...)`, a `ChangeNotifier` bean with `@NotifyListeners` |
| `spasset` | A `@Value('asset:...')` parameter |
| `splifecycle` | An `@EventListener` for `AppLifecycleStateEvent` |
| `spwidgettest` | A widget test with `springBootTest` and `SpringScope` |
| `sploaderpainter` | A `@ThemeLoaderKind` painter (`ThemeLoaderPainter<P>`) |

### Themes and the app widget

In `application.yml` and in `.properties` files, with the same prefixes in both:

| Prefix | Inserts |
|---|---|
| `spapp` | `spring.flutter.app`: type, title, debug banner |
| `sptheme` | `spring.flutter.theme`: active theme, seed color, fonts, shapes, components, the dark theme |
| `spthemeall` | Every theme property, commented out, with its values (YAML only) |
| `spthemenew` | A custom theme (`themes.<name>`, `extends`), in its own file in YAML |
| `spcolors`, `sptypography`, `spshape` | Color roles, fonts per text role, the shape scale |
| `spcolorobject` | A color with `alpha` and/or `mix: { with, amount }` |
| `spcomponents`, `sptokens` | Material components from the tokens, the app's own tokens |
| `spfonts` | `spring.flutter.fonts`: auto-load, exclude |
| `sploader`, `sploaderkind` | A built-in loader, a loader of a `@ThemeLoaderKind` class with phases and `web:` |
| `spsplash` | `splash`: background, logo, title, loader, minimum time, exit |

## Creating a project

The language server also creates Spring Boot applications, like Spring Initializr. Zed extensions cannot add commands to the command palette yet, so run it in a terminal (Zed's terminal works: `` Ctrl-` ``). The extension keeps the downloaded server at a fixed path once a Dart file has been opened:

```sh
# macOS
"$HOME/Library/Application Support/Zed/extensions/work/dart-spring/bin/dart_spring_lsp" create my_app

# Linux
~/.local/share/zed/extensions/work/dart-spring/bin/dart_spring_lsp create my_app
```

```powershell
# Windows
& "$env:LOCALAPPDATA\Zed\extensions\work\dart-spring\bin\dart_spring_lsp.exe" create my_app
```

| Option | Does |
|---|---|
| `create my_app` | A new folder `my_app` with the project |
| `create .` | The project in the current, empty folder |
| `--name=shop` | The package name; by default from the folder name |
| `--no-pub` | Skip `dart pub get` and `build_runner build` |
| `--force` | Write into a folder that is not empty |
| `--help` | The options |

It writes `bin/main.dart` with `@SpringBootApplication`, a `@ConfigurationProperties('app')` class, a `@Service`, an `ApplicationRunner`, `lib/resources/application.properties` and `application-dev.properties`, a `springBootTest` test, and a `pubspec.yaml` with `spring_boot_dart`, the logging and test starters and the generator. Then:

```sh
cd my_app
dart run bin/main.dart     # my_app says: Hello, world!
dart test
```

## Configuration

Navigation, hovers and checks work as soon as the extension is installed. Two settings in Zed's `settings.json` add the colours.

**Semantic highlighting** for SpEL, placeholders, pointcuts and SQL:

```json
{
  "languages": {
    "Dart": { "semantic_tokens": "combined" },
    "YAML": { "semantic_tokens": "combined" },
    "Properties": { "semantic_tokens": "combined" }
  }
}
```

**A colour for a closure's parameters.** A rule maps the server's `closureParameter` token to a theme style such as `variable.parameter.closure`, which the [Farum Azula Themes](themes.md) colour. The [Flutter Tools](flutter-tools.md) extension ships these rules with its Dart language. With another Dart extension, add them yourself:

```json
{
  "global_lsp_settings": {
    "semantic_token_rules": [
      { "token_type": "class", "token_modifiers": ["annotation"] },
      { "token_type": "property", "token_modifiers": ["annotation"] },
      { "token_type": "method", "token_modifiers": ["annotation"] },
      { "token_type": "annotation" },
      { "token_type": "parameter" },
      { "token_type": "closureParameter", "style": ["variable.parameter.closure"] }
    ]
  }
}
```

A rule without a style takes a token's colour away and leaves it to the tree-sitter colours. The Dart analysis server marks every parameter `parameter`, so without that rule its token would hide `closureParameter`; the first four rules keep annotations in their own colour. Zed honours a rule without a style only when it is the first rule for that token type, so give each type at most one, before its other rules.

**A server of your own.** The extension looks for the language server in this order, so a local build wins:

1. `lsp.dart-spring.binary.path` in Zed's settings, with `binary.arguments` if needed;
2. `dart_spring_lsp` on the `PATH`, built from the repository with `dart run tool/install_language_server.dart` (it goes into `~/.pub-cache/bin`);
3. the binary downloaded from the GitHub release `v<version>` (macOS Apple Silicon, Linux x64 and arm64, Windows x64), or from the latest release when that one has no binaries.

```json
{
  "lsp": {
    "dart-spring": {
      "binary": { "path": "/path/to/dart_spring_lsp" }
    }
  }
}
```

## Troubleshooting

**No navigation or hovers at all.** The server is downloaded the first time a Dart file is opened; Zed shows the download in the status bar. Check Zed's log (`zed: open log`) and the server's log (`dev: open language server logs`, `dart_spring`).

**"no prebuilt language server for this platform".** There are no binaries for Intel Macs and other platforms. Clone the spring_core_dart repository, run `dart run tool/install_language_server.dart`, and make sure `~/.pub-cache/bin` is on the `PATH` Zed sees.

**No SpEL or placeholder colours.** Turn on `semantic_tokens` for Dart, YAML and Properties (see [Configuration](#configuration)).

**Keys of starters are not completed, or the theme is not checked.** Run `dart run build_runner build` so the package has `lib/spring_gen/spring_metadata.json`. A dependency published before metadata existed shows `No Spring metadata in ...` at the top of the file.

**A bean is reported missing although it exists.** Beans declared by hand (`BeanDefinition(...)`) are not indexed. The server parses Dart syntax only, so it also works before `pub get`.

## Links

- [Source of the extension](https://github.com/farum-azula/spring_core_dart/tree/main/extensions/zed/dart_spring)
- [Source of the language server](https://github.com/farum-azula/spring_core_dart/tree/main/extensions/language_server)
- [Releases with the language server binaries](https://github.com/farum-azula/spring_core_dart/releases)
- [Installation](installation.md)
- [Spring for Dart documentation](../../docs/index.md)
