
# Imports

`spring.config.import` reads more configuration from inside a config file, or from the command line. Use it to split a large configuration into several files, or to add what an operator provides: local overrides, mounted secrets, a file on a config server.

## Why

One `application.yml` for everything grows hard to read. Imports let each concern have its own file (`db.yml`, `themes/ocean.yml`) while the application still sees one set of keys. They also connect the configuration to its environment: a Kubernetes secret mounted as files, or an override file that exists only on one machine.

## Example

```yaml
# lib/resources/application.yml
spring:
  config:
    import:
      - resources:db.yml                 # packaged, required
      - optional:file:./local.yml        # next to the program, may be missing
      - optional:configtree:/run/secrets/  # Kubernetes or Docker secrets
shop:
  title: NEON Books
```

```properties
# lib/resources/application.properties: the same
spring.config.import=resources:db.yml,optional:file:./local.yml,optional:configtree:/run/secrets/
shop.title=NEON Books
```

```yaml
# lib/resources/db.yml
db:
  url: postgres://localhost/shop
  pool-size: 5
```

```text
/run/secrets/db/password      → db.password=<the file's content>
```

## Location forms

The same forms work in `spring.config.import`, `spring.config.location` and `spring.config.additional-location`.

| Form | What is read | Notes |
|---|---|---|
| `resources:db.yml` | A file of `lib/resources/`, embedded by the generator | Works in every build: VM, AOT, Flutter, web |
| `resources:config/` | A directory of `lib/resources/`: the `application*` files in it (or those of `spring.config.name`) | Counts as found only when a file is found in it |
| `file:./local.yml` | A file of the file system | Not on the web |
| `file:./config/` | A directory: its `application*` files | Must end with `/` |
| `file:./config/*/` | Each subdirectory, in alphabetical order | One `*`, as the last directory; `file:./config/*/app.yml` reads that file in each |
| `local.yml` | A plain path: a file, as with `file:`. In an import, relative to the importing file | A `resources:` file imports `resources:` siblings this way |
| `optional:...` | Any of the above; missing is fine | Put before the whole location |
| `file:./conf[.yml]` | A file without a known extension, read as YAML | The hint is matched without case |
| `file:./legacy.properties[encoding=iso-8859-1]` | A `.properties` file in that encoding | UTF-8, ISO-8859-1, US-ASCII (Java's names and aliases). YAML is always UTF-8 |
| `file:./legacy.conf[.properties][encoding=latin1]` | Both hints, in any order | |
| `configtree:/run/secrets/` | A config tree: each file is one property | See [Config trees](#config-trees) |
| `configtree:/run/*/` | Each subdirectory as a config tree | |
| `https://cfg.example.com/shop.yml` | A file over HTTP or HTTPS | Asynchronous start only; see [HTTP](#over-http) |
| `package:shop_defaults/defaults.yml` | A file of a Dart package, through the program's package config | Not on the web nor in AOT executables |
| `asset:config/shop.yml` | A Flutter asset | With `spring_boot_starter_flutter`; read asynchronously |
| `x;y` | A group: one location made of several | Optional when its first entry is `optional:`; found when any entry finds something |

A location without a known extension (`.properties`, `.yml`, `.yaml`) must end with `/` (a directory) or carry an extension hint. Other formats need a `PropertySourceLoader` of your own, given to `ConfigDataEnvironment(loaders:)`.

## Precedence

- An imported file **overrides the file that imports it**.
- An imported file gets its own `-{profile}` variants, which win over the profile files of the importing file: when `application.yml` imports `db.yml`, `db-dev.yml` wins over `application-dev.yml`.
- Relative locations are relative to the importing file.
- Given on the command line (`--spring.config.import=...`) or as `SPRING_CONFIG_IMPORT`, imports form a group above every location.
- A file is read once, so import cycles do no harm. Named at several places, it counts at the place that wins: the later item of a list, the command line's import before `additional-location` before the locations. The encoding hint written at that place applies.

## Placeholders in imports

`${...}` in an import is resolved against the command line, the environment and the documents read so far, when the importing document's imports are read:

```yaml
spring:
  config:
    import: optional:file:${SHOP_CONFIG_DIR:/etc/shop}/shop.yml
```

An `optional:` import whose placeholder cannot be resolved is skipped. A required one fails the start.

## Imports in profile files

An import in a profile file (`application-prod.yml`) or in a document limited to a profile is read only with that profile, and it is as required as any other: a missing required file fails the start. Use it for files that exist only in one environment:

```yaml
# lib/resources/application-prod.yml
spring:
  config:
    import: configtree:/run/secrets/
```

## Config trees

Kubernetes mounts secrets and config maps as directories of files, and Docker does the same with secrets. A `configtree:` location reads such a directory: every file below it is one property named by its path, whose value is the file's content.

```text
/run/secrets/
  db/
    password        "s3cret\n"   → db.password=s3cret
  mail.api-key      "abc"        → mail.api-key=abc
```

- The location must end with `/`, even an `optional:` one, or the start fails.
- One trailing newline is removed from each value.
- Entries whose name starts with `..` (Kubernetes' internal links) are skipped.
- A required tree whose directory is missing fails the start; with a wildcard, one without subdirectories fails.
- Values are strings, bound and converted like any other property.
- Only directories of the file system are read, so not on the web.

## Over HTTP

```bash
dart run bin/main.dart --spring.config.import=optional:https://config.neon.books/shop.yml
```

- The file is fetched with a `GET` request; a status of 400 or more fails the read.
- An `optional:` HTTP location is first checked with a `HEAD` request (a `GET` when the server refuses `HEAD`); a 404 or a connection error skips it.
- Reading is asynchronous, so the application must start with `runApplicationAsync` (or `SpringApplication.runAsync`; Flutter apps do). The synchronous `runApplication` fails with `the resource can only be read asynchronously; use processAndApply()`.
- Reading needs `dart:io`, so it does not work in a Flutter web app.
- No headers, credentials or retries are sent. For a server that needs a token, or for a vault, add the values yourself with an `EnvironmentPostProcessor` (below) or a `ProtocolResolver` of your own.

## Your own kind of location

Two extension points cover what the built-in forms do not.

**A `ProtocolResolver`** teaches the resource loader a prefix. Config imports, `@PropertySource` and `@Value` resources then accept it:

```dart
// memory:shop.yml served from a map, for a tool or a test.
final application = SpringApplication(
  [appBeans],
  resourceLoader: DefaultResourceLoader(
    protocolResolvers: [
      InMemoryProtocolResolver('memory:', {'shop.yml': 'shop:\n  title: Test\n'}),
    ],
  ),
);
// spring.config.import=memory:shop.yml
```

**An `EnvironmentPostProcessor`** changes the environment before any bean exists: it can fetch settings from a server, add a property source, activate profiles or add imports. One ordered before `EnvironmentPostProcessor.configDataOrder` runs before the files are read:

```dart
// Imports the secret files the operators mount in ./secrets/.
class LocalSecrets implements EnvironmentPostProcessor, Ordered {
  @override
  int get order => EnvironmentPostProcessor.configDataOrder - 1;

  @override
  void postProcessEnvironment(
    ConfigurableEnvironment environment,
    SpringApplication application,
  ) {
    environment.propertySources.addLast(
      MapPropertySource('secrets', {
        'spring.config.import': 'optional:file:./secrets/',
      }),
    );
  }
}

final application = SpringApplication(
  [appBeans],
  environmentPostProcessors: [LocalSecrets()],
);
```

## Not supported

- `env:` imports.
- `resources*:` and classpath wildcards in config locations.
- XML properties files (`x.xml` fails the start; an `optional:` one is skipped).
- A Spring Cloud Config, Consul or Vault client: there is no `configserver:` or `vault:` location. Use an HTTP import or an `EnvironmentPostProcessor`.

## In Spring (Java)

The same key and the same rules as Spring Boot's `spring.config.import`, except:

- Each entry of a `;` group is read by its own prefix, so `x.yml;configtree:/run/secrets/` reads the tree. Spring Boot picks the resolver of the whole group from its first entry.
- A relative import in a file found through a wildcard location is relative to that file. Spring Boot resolves it against the wildcard pattern.
- A `configtree:` location that is a file counts as missing, so `optional:` skips it; Spring Boot fails.
- Placeholders in an import are resolved when the import is read, not at the first pass.

## See also

- [Config files](config-files.md)
- [Profiles](profiles.md)
- [Overview: which source wins](index.md)
- [Resources](../../spring-core-dart/resources/resource.md)
- [Property sources](../../spring-core-dart/config/property-source.md)
