Metadata for editors

For every package with Spring code, the builder spring_metadata writes lib/spring_gen/spring_metadata.json. It describes the Spring side of the package for editors and tools: the configuration properties with their types, descriptions and defaults, the allowed values, the beans, the profiles and, for Flutter apps, the loader kinds and the routes.

Everything in the file comes from the code. You never write it or edit it: a /// comment on a field becomes the property's description, a literal initializer its default, an enum type its list of values.

Why

An editor that knows the properties can complete server.port in application.yml, show its description on hover, and flag server.prot or port: abc. To know them, it needs a description of every key of the app and of every starter it uses. Spring Boot has the same need and the same answer: its annotation processor writes META-INF/spring-configuration-metadata.json from the Java classes and their Javadoc.

Deriving the file from the code keeps it right. The starters read their settings through the same @ConfigurationProperties classes the metadata is made from, so the description of a property and the way it is read cannot drift apart.

When it is written

The builder runs for every package that depends on the generator. It writes the file when a .dart file of lib/ or bin/ (generated files left out) contains one of these words: ComponentScan, SpringBootApplication, AutoConfigurationModule, ConfigurationProperties, BeanDefinition<, @Component, @Service, @Configuration, @Bean, @ThemeLoaderKind, @ScreenRoute, @RouteShell. A package without Spring code gets no file.

The file is sorted, and its keys are in a fixed order, so it changes only when the code changes. This makes it easy to review in a diff.

Like the main builder, it keeps the file it wrote before while the sources have errors: the build logs a warning (lib/spring_gen/spring_metadata.json is kept unchanged until this error is fixed:) and writes the old content again. So build_runner watch does not delete it on every half-typed line.

Example

A @ConfigurationProperties class of spring_boot_starter_web:

// spring_boot_starter_web/lib/src/config/web_properties.dart
@ConfigurationProperties('server')
class ServerSettings {
  /// The port. `0` picks a free one; the real port is then in
  /// `local.server.port`.
  int port = 8080;

  /// What happens to running requests when the server stops: `graceful`
  /// accepts no new connections and lets them finish, `immediate` cuts
  /// them.
  Shutdown shutdown = Shutdown.graceful;
  // ...
}

enum Shutdown {
  /// Stop accepting connections and let running requests finish, for up
  /// to `spring.lifecycle.timeout-per-shutdown-phase` (30 seconds by
  /// default); then close what is left. The default.
  graceful,

  /// Close every connection right away, cutting running requests.
  immediate,
}

The entries the builder writes for it, in that package's lib/spring_gen/spring_metadata.json:

{
  "properties": [
    {
      "name": "server.port",
      "type": "int",
      "description": "The port. `0` picks a free one; the real port is then in `local.server.port`.",
      "default": 8080,
      "deprecated": null,
      "source": "package:spring_boot_starter_web/src/config/web_properties.dart",
      "line": 35,
      "class": "ServerSettings"
    },
    {
      "name": "server.shutdown",
      "type": "Shutdown",
      "description": "What happens to running requests when the server stops: `graceful` accepts no new connections and lets them finish, `immediate` cuts them.",
      "default": "graceful",
      "deprecated": null,
      "source": "package:spring_boot_starter_web/src/config/web_properties.dart",
      "line": 44,
      "class": "ServerSettings"
    }
  ],
  "hints": [
    {
      "name": "server.shutdown",
      "values": [
        {
          "value": "graceful",
          "description": "Stop accepting connections and let running requests finish, for up to `spring.lifecycle.timeout-per-shutdown-phase` (30 seconds by default); then close what is left. The default."
        },
        {
          "value": "immediate",
          "description": "Close every connection right away, cutting running requests."
        }
      ]
    }
  ]
}

The description is the first paragraph of the /// comment, on one line. The default Shutdown.graceful is written the way a property value is written, graceful. The enum adds a hint that lists its constants, each with its own /// text.

What the file contains

{
  "version": 1,
  "package": "neon_farum_azula",
  "properties": [ ... ],
  "hints": [ ... ],
  "beans": [ ... ],
  "profiles": [ "release", "web" ],
  "loaderKinds": [ ... ],
  "routes": [ ... ]
}
Key Content Present
version The format's version, 1. Always
package The package's name. Always
properties The configuration keys the package binds or reads. Always (may be empty)
hints The values, ranges and warnings of keys. Always (may be empty)
beans The beans the package defines. Always (may be empty)
profiles The profile names the package uses. Always (may be empty)
entities, repositories The data layer of spring_boot_starter_data: see Data. Only with a data layer
loaderKinds The @ThemeLoaderKind classes. Only when there are some
routes, shells The @ScreenRoute screens and @RouteShell shells. Only when there are some
theme The schema of spring.flutter.theme.*: its types and properties. Only in the metadata of spring_boot_starter_flutter itself

Properties

Bound by @ConfigurationProperties

For each class with @ConfigurationProperties('prefix'), and for each @Bean method with @ConfigurationProperties('prefix') (then its return type's class), the builder lists one property per bound member. The members are found as the binder finds them:

Each entry has these keys:

Key Derived from
name The prefix, a dot, and the member's name in kebab case (baseUrl is base-url, apiURL is api-url). @Name('import') on the member gives another last segment.
type The Dart type, as written (int, Duration, List<String>, int?).
description The first paragraph of the /// comment of the field (or, for a constructor parameter that initializes a field, of that field), on one line. null without a comment.
default The literal initializer of a field, or the default value of a constructor parameter. See below.
deprecated The message of @Deprecated('...') on the member, else null.
source, line Where the member is declared: package:<package>/<path> for a file in lib/, the path for one in bin/; the line of its name.
class The class that declares it.

Nested values are followed:

Member type Property names
A class of the same package (not abstract, not an enum) Its members under the member's name: server.compression.min-response-size
A list or set of such a class name[*].field
A map with such a class as values name.*.field
A map of plain values name.*, typed with the value type
A list of plain values name itself (a comma-separated text binds there too)

Types of the SDK and of other packages (Duration, DataSize, Uri) are values, not groups. A class is not followed into itself, nor more than 8 levels deep.

Defaults

Only a plain literal gives a default; anything else (a call, a constant from elsewhere, a string with $ or \) gives null:

Written default
true, false true, false
8080, 0.5 8080, 0.5
'plain', r"plain" "plain"
[], {}, const [] [], {}
['a', 'b'] (literals only) ["a", "b"]
Shutdown.graceful (an enum constant of the field's type) "graceful" (kebab case)
Duration(seconds: 30) (one unit) "30s" (ms, s, m, h, d)
DataSize.ofMegabytes(10) "10MB" (B, KB, MB, GB, TB)
null null

A null default and no default look the same: the format has one default key.

Keys that are only read

Keys that code reads without binding them are listed too, so the editor knows them:

They have no description. When a @ConfigurationProperties class binds the same key, its entry wins, as it has the better description.

Hints

A hint narrows the values of one property. The builder writes one per property that has something to say:

Source in the code In the hint
An enum-typed property values: each constant in kebab case, with its /// text as description
@PropertyValues(['plain', 'json']) on a String field values: those texts, without descriptions
@PropertyValues.provider('profiles') provider: "profiles": the editor lists the project's profiles
@Range(0, 65535) range: [0, 65535]
@WarnValues([...], 'why') warn: [{ "values": [...], "message": "why" }] (enum constants in kebab case)

@Range, @WarnValues and @PropertyValues come from spring_core_dart and are for the metadata only: they check nothing at run time. For a list property, the hint is named name[*], as it describes the items.

// spring_boot_starter_flutter: the port of the web dev server
/// The port of the web dev server; 0 picks a free port.
@Range(0, 65535)
@WarnValues(
  [1, 7, 9, 11, /* ... */ 6697, 10080],
  "Browsers refuse to open this port (Chromium's list of blocked ports).",
)
final int? port;
{
  "name": "spring.flutter.web.dev-server.port",
  "range": [0, 65535],
  "warn": [
    {
      "values": [1, 7, 9, 11, "...", 6697, 10080],
      "message": "Browsers refuse to open this port (Chromium's list of blocked ports)."
    }
  ]
}

(The "..." stands for the values left out here.)

Beans

Every bean the main builder's scan finds, and every bean a library defines by hand with BeanDefinition<T>(...) in plain Dart (as the starters' auto-configurations do, read from the syntax tree):

{
  "name": "basket",
  "type": "Basket",
  "types": ["Basket"],
  "scope": "singleton",
  "primary": false,
  "qualifiers": [],
  "profiles": [],
  "conditions": [],
  "source": "package:neon_books_app/src/basket/basket.dart",
  "line": 31,
  "injects": [
    { "parameter": "_shop", "type": "ShopClient", "qualifier": null }
  ],
  "members": [
    { "name": "add", "kind": "method", "type": "Future<void>", "parameters": ["Book book"] },
    { "name": "clear", "kind": "method", "type": "void", "parameters": [] }
  ]
}
Key Content
name, type The bean's name and class.
types Every type the bean can be injected by, its own first.
scope, primary, qualifiers As declared.
profiles The profile names of its @Profile conditions.
conditions Its other conditions, as written (@ConditionalOnProperty(...)); a @Bean method lists its class's conditions first.
injects Its injection points (constructor parameters, injected fields and methods): the parameter, its type and its qualifier. @Value points are left out.
members What a SpEL expression can reach on the bean: public getters, fields and methods of the class and its supertypes (not Object's). A method lists its parameters as Type name, named ones in braces, optional ones in brackets.

An editor uses them to resolve #{@basket.count}, and to show which bean an injection point gets (none, or several without @Primary or @Qualifier).

Profiles

The profile names of the package, sorted: the names in its @Profile expressions ((dev | local) & !ci gives dev, local, ci), and the <name> of every application-<name>.yml, .yaml or .properties file in its lib/resources/. This site's application-release.yml and application-web.yml give ["release", "web"].

Loader kinds

One entry per @ThemeLoaderKind class, found in the source text: the kind's name, the class, its source and line, and props, the top-level keys that the package's own themes give the loaders of that kind (without kind, phases, tracks, web and web-sha256). From this site:

"loaderKinds": [
  {
    "name": "spring-leaf",
    "class": "SpringLeafLoader",
    "source": "package:neon_farum_azula/src/splash/spring_leaf_loader.dart",
    "line": 6,
    "props": ["background", "leaf", "ring", "title"]
  }
]

This list is also how a library's loader kinds become known to an app: the typed keys builder of an app reads the loaderKinds of each package in its dependencies, so a theme of the app may name them.

Routes and shells

With spring_boot_starter_flutter_navigation, each @ScreenRoute screen is listed with its path, name, class and source, and what else it declares: title, params, extra, shell, branch, content, notFound, preAuthorize, and the description, image, index: false, link: false and paths of @RouteInfo. Each @RouteShell is listed with its class, source and branches. Routes are sorted by path. From this site:

"routes": [
  {
    "path": "/components/{*path}",
    "name": "docs-page",
    "class": "DocsPage",
    "source": "package:neon_farum_azula/src/pages/docs/docs_page.dart#DocsPage",
    "title": "#{docs.title}",
    "content": "resources:content/components/"
  }
]

The editor completes paths with them, and the pages for search engines are made from them.

The theme

The metadata of spring_boot_starter_flutter has one more key, theme: the types and properties of spring.flutter.theme.* (each with its type, description, default, and whether it works at the root, inside themes.<name>, or both). The builder copies it from the starter's tool/theme_metadata.json, the same file the theme's documentation is made from. Other packages do not repeat it: tools take it from the starter's file.

Publishing

Commit spring_metadata.json with the other generated files. It is in lib/, so it is published with the package, as META-INF is part of a jar. A tool that knows an app's .dart_tool/package_config.json finds the metadata of the app and of every package it depends on, at <package>/lib/spring_gen/spring_metadata.json. The Spring for Dart language server reads them that way, for completion, hovers and checks in application*.yml, .properties and Dart.

A JSON Schema for any editor

An editor without the language server can still check application.yml with a JSON Schema. The Spring for Dart repository has a tool that makes one from the metadata of an app and its dependencies:

# In the spring_core_dart repository; run `dart pub get` and the build in the app first.
dart run tool/spring_schema.dart path/to/app
# or: dart run tool/spring_schema.dart path/to/app --out schema.json

It writes path/to/app/spring-application.schema.json (JSON Schema draft 2020-12). What it puts in:

Point a YAML file at the schema with a first line. The path is relative to the YAML file; a URL works too:

# yaml-language-server: $schema=../../spring-application.schema.json
spring:
  profiles:
    active: dev

Editors that use the YAML language server (VS Code with the YAML extension, Zed, Neovim and others) then complete the keys, show their descriptions and check the values: a wrong type, a value outside a hint's list or range. Unknown keys are allowed (additionalProperties: true), as a key may be read by code the metadata does not describe; the language server's own checks are stricter.

In Spring (Java)

Spring Boot's spring-boot-configuration-processor writes META-INF/spring-configuration-metadata.json at compile time, from @ConfigurationProperties classes and their Javadoc. The differences:

See also