@ConfigurationProperties
A @ConfigurationProperties class gathers every property under a prefix into one typed object. Each field is bound from the key with the field's name in kebab case (maxBasketSize reads shop.max-basket-size), converted to the field's type, and the object is injected like any bean.
The annotation lives in spring_core_dart; spring_boot_dart does the binding and the validation at start-up.
Why
@Value reads one key. A feature with ten settings needs a place where they are listed, typed and checked:
- the keys are in one class, with their defaults and
///comments (which the editor shows as completion); - values are converted once, at the start:
30sbecomes aDuration,10MBaDataSize; - a wrong value stops the start with the key's name, instead of failing later in production;
- the class is a bean, so services, controllers and widgets inject it.
Example
# lib/resources/application.yml
shop:
title: NEON Books
max-basket-size: 20
checkout-timeout: 30s
currencies: [EUR, USD]
payment:
provider: stripe
timeout: 5s
servers:
- name: eu
url: https://eu.neon.books
- name: us
url: https://us.neon.books
headers:
X-Shop: neon
warehouses:
berlin:
capacity: 5000
open: true
@ConfigurationProperties('shop')
@Validated()
class ShopProperties {
/// The shop's name, shown in the header.
@NotBlank()
String title = 'Shop'; // shop.title
/// The most books in one basket.
@Min(1)
@Max(100)
int maxBasketSize = 10; // shop.max-basket-size
Duration checkoutTimeout = const Duration(minutes: 1);
List<String> currencies = ['EUR']; // a comma list or [0], [1]
Payment payment = Payment(); // a nested object
List<Server> servers = []; // a list of objects
Map<String, String> headers = {}; // a map of values
Map<String, Warehouse> warehouses = {}; // a map of objects
}
class Payment {
String provider = 'none';
Duration timeout = const Duration(seconds: 10);
}
class Server {
String name = '';
String url = '';
}
class Warehouse {
int capacity = 0;
bool open = false;
}
@Service()
class Shipping {
Shipping(this.shop);
final ShopProperties shop;
int capacityOf(String city) => shop.warehouses[city]?.capacity ?? 0;
}
No @EnableConfigurationProperties or @ConfigurationPropertiesScan is needed: the annotation makes the class a bean, and the generator writes its introspection. Fields are bound directly, without getters and setters.
Parameters
| Parameter | Default | Meaning |
|---|---|---|
prefix |
required | The common start of the keys, in canonical form: shop, my-app, spring.main. '' binds keys without a prefix |
name |
from the class | The bean name |
ignoreUnknownFields |
true |
false stops the start for keys under the prefix that bind to nothing: The elements [db.urll] were left unbound. OS environment variables are not checked |
ignoreInvalidFields |
false |
true keeps the field's default when a value cannot be converted, instead of failing |
Binding rules
- A field keeps its default when its key is not set.
- Relaxed names:
shop.max-basket-size,shop.maxBasketSize,--shop.max-basket-size=...andSHOP_MAX_BASKET_SIZEall bindmaxBasketSize. - Nested objects bind from deeper keys (
shop.payment.timeout). A nullable nested object none of whose keys is set staysnull. - A list comes whole from the highest source that has it: a comma value, a YAML list, or indexed keys (
APP_HOSTS_0_as a variable).--app.hosts[0]=xreplaces a three-element list from a file; it does not change its first element. Indexes start at 0, without gaps. - Map entries are merged across sources, the higher source winning per key. Keys keep the form they are written in (
X-Shop);[x.y]keeps the dots; for scalar values the rest of the name is the key (app.headers.a.b=1gives the keya.b). - Elements, keys and values are converted through the conversion service:
List<Duration>,Map<String, int>, enums by lenient name. A value that cannot be converted stops the start:app.ports[0]: failed to convert to int (was "x"). - Placeholders in values are resolved; one that cannot be resolved is kept as written.
@RawValue()on aStringfield keeps${...}as written (for a template the receiver resolves itself).
Immutable classes: constructor binding
A class whose only constructor has parameters is bound through that constructor, also for nested classes. This is Spring Boot 3's default for immutable classes:
@ConfigurationProperties('pool')
class PoolProperties {
const PoolProperties(
this.url, { // required: pool.url must be set
@DefaultValue('10') required this.maxSize, // 10 when not set
this.timeout = const Duration(seconds: 5), // a Dart default works too
this.owner, // nullable: null when not set
this.replicas = const [], // pool.replicas[0].host=...
});
final String url;
final int maxSize;
final Duration timeout;
final String? owner;
final List<Endpoint> replicas;
}
A parameter without a property takes its @DefaultValue, else its Dart default, else null when it is nullable. A required non-nullable parameter with none of them stops the start: pool.url: no value bound for the required constructor parameter 'url' of PoolProperties. A missing collection is empty, and a missing nested object is created with its own defaults.
More annotations
| Annotation | On | Effect |
|---|---|---|
@Name('import') |
field or constructor parameter | Binds from another key; needed when the key is a Dart keyword (import, default) |
@DefaultValue('10') |
constructor parameter | The value used when the key is not set, written as a property value |
@DurationUnit(ChronoUnit.seconds) |
Duration field |
A plain number is read in that unit (app.timeout=60 is 60 s). No months or years |
@DataSizeUnit(DataUnit.megabytes) |
DataSize field |
A plain number is read in that unit |
@RawValue() |
String field |
Placeholders are not resolved |
@Range(min, max), @WarnValues([...], 'why'), @PropertyValues([...]) |
field | Bounds, warned values and allowed values for the editor metadata |
On a @Bean method
@ConfigurationProperties('pool') on a @Bean method binds the object the method returns, even a class of another package (the generator writes its introspection). @Validated() on the method validates it.
@Configuration()
class PoolConfiguration {
// Binds pool.* into a class of a library that knows nothing about Spring.
@Bean()
@ConfigurationProperties('pool')
PoolSettings poolSettings() => PoolSettings();
}
Validation at start-up
With @Validated(), the constraint annotations are checked once the values are bound. An invalid value stops the start with a report that names the key:
Binding to target properties under 'shop' failed:
- shop.max-basket-size: must be greater than or equal to 1 (was "0")
Three ways validate a bound object:
@Validated()on the class: its constraints (@NotBlank(),@Min,@Size...) are checked.- A
Validatorbean namedconfigurationPropertiesValidatorchecks every bound object it supports. - A properties class that is itself a
Validatorvalidates itself.
@Validated() on a @ConfigurationProperties class means "validate after binding", not method validation. In Flutter apps @Size is named @SizeConstraint. See Validation.
Binder: structures without a class
Binder binds a part of the configuration to a type on demand, with the same rules. It is for code that needs a list or a map once, such as a starter reading its settings:
final binder = Binder.get(environment);
// A YAML list, indexed keys or a comma list: all give a List.
final hosts = binder
.bind('shop.hosts', const ListType(ClassType<String>()))
.orElse(const []);
final limits = binder
.bind('shop.limits', const MapType(ClassType<String>(), ClassType<int>()))
.orElse(const {});
BindResult has get, isBound, orElse, orElseGet, orElseThrow, ifBound and map. A BindHandler passed to bind is told about each property (onStart, onSuccess, onFailure, onFinish); its onFailure(name, error) returns whether the failure counts (false leaves the property unbound).
Editor metadata
The generator writes the class's keys, types, defaults and /// comments to lib/spring_gen/spring_metadata.json, the counterpart of spring-configuration-metadata.json. Nothing is written by hand. A map field is listed as headers.*, a list of classes as servers[*].url. See Metadata.
In Spring (Java)
@ConfigurationProperties("shop")
@Validated
public class ShopProperties {
@NotBlank private String title = "Shop";
@Min(1) @Max(100) private int maxBasketSize = 10;
// getters and setters
}
@SpringBootApplication
@ConfigurationPropertiesScan
class NeonBooks { ... }
Differences:
- No
@EnableConfigurationPropertiesor@ConfigurationPropertiesScan; no getters and setters. - A missing non-nullable scalar in a constructor stops the start; Spring passes
null. - Constructor binding only for a class whose only public generative constructor has parameters; there is no
@ConstructorBindingto pick one of several. BindHandler.onFailurereturns whether the failure counts, instead of a replacement value; errors are collected and reported together.