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 in the spring_core_dart repository
Language server extensions/language_server

The extension lives in the framework's repository, not in the repository of the other Zed extensions. See Installation.

What it gives

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:

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

  final PaymentService payments;
  final String shopName;
}

hovering PaymentService shows:

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:

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.

Highlighting inside strings

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

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:

An unknown key looks like this in the diagnostics panel:

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:

A table or column the database has but no entity declares is not checked. See Queries and Derived queries.

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:

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

  final Repository repository;

}

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

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

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

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:

{
  "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 colour. The Flutter Tools extension ships these rules with its Dart language. With another Dart extension, add them yourself:

{
  "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.
{
  "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).

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.