Inversion of control and dependency injection
In a plain program, each object creates the objects it uses, or main creates them all by hand. With Spring you only declare your classes and what each one needs. A container creates the objects, passes each one its dependencies, configures them, and closes them at the end. Control over creation moves from your code to the container: this is inversion of control. Passing an object its dependencies from outside, instead of letting it create them, is dependency injection.
The problem
A small order service, written the usual way:
class OrderService {
// The service builds what it uses.
final _repository = OrderRepository(Database.open('orders.db'));
final _payments = CardGateway(apiKey: Platform.environment['CARD_KEY']!);
final _mailer = Mailer('smtp.example.com');
Future<void> place(Order order) async {
await _payments.charge(order.total);
await _repository.save(order);
await _mailer.send(order.email, 'Thank you for your order');
}
}
It works, but:
- It is hard to test. A test of
placecharges a real card, writes a real file and sends a real mail. There is no way to pass a fake. - It is hard to change. Using a fake gateway in development means an
ifin the class. Using another database means editing it. - The configuration is spread out. The file name, the key and the mail host are read in three places, each in its own way.
- The wiring is repeated. Every class that needs a
Mailercreates its own, with its own settings. - It does not scale. Each new feature lands in the classes that already exist: a second payment method, a loyalty bonus after an order, a log line around every charge all mean editing
OrderService. With dozens of services, every change touches code that already works, and the classes grow into knots that nobody dares to change. - It works against SOLID. The principles that keep a large code base healthy are hard to follow when each class builds its own dependencies. Each one is shown below with a small example.
Moving the creation to main fixes the testing, but main grows with every class, must create them in the right order, and every new constructor parameter means editing it and every test that builds the class.
SOLID, one principle at a time
Each principle in a few lines: the usual way first, then with Spring.
S: single responsibility. A class should have one reason to change.
// Before: placing orders AND choosing and configuring the mail server.
class OrderService {
final _mailer = Mailer(host: 'smtp.example.com', port: 587);
}
// With Spring: the service only uses a Mailer. Which one, and how it is
// configured, is the Mailer bean's business.
@Service()
class OrderService {
OrderService(this.mailer);
final Mailer mailer;
}
O: open for extension, closed for modification. New behaviour should come from new code, not from edits to code that works.
// Before: every new reaction to an order is a new line in place().
Future<void> place(Purchase purchase) async {
await repository.save(purchase);
await mailer.sendReceipt(purchase);
await points.add(purchase.customer, 10); // edited in for the bonus
}
// With Spring: a new reaction is a new class; place() never changes.
@Component()
class LoyaltyBonus implements PurchaseListener {
@override
Future<void> onPlaced(Purchase purchase) async { /* add points */ }
}
OrderService asks for List<PurchaseListener> and gets every implementation; see Patterns that extend themselves.
L: Liskov substitution. Any implementation of an interface must work where the interface is expected.
// Before: callers check the concrete type, so a new gateway breaks them.
if (gateway is CardGateway) { gateway.charge(total); } else { /* ... */ }
// With Spring: callers only know PaymentGateway; the dev profile's fake
// and the real one are interchangeable.
@Component()
@Profile(['dev'])
class FakeGateway implements PaymentGateway {
@override
Future<void> charge(double amount) async {}
}
I: interface segregation. Depend on the small interface you use, not on a big class.
// Before: the report needs one query but depends on the whole repository.
class SalesReport {
SalesReport(this.repository); // OrderRepository: 30 methods
final OrderRepository repository;
}
// With Spring: ask for the narrow interface; the repository bean that
// implements it is injected.
abstract interface class SalesTotals {
Future<double> totalFor(DateTime month);
}
@Service()
class SalesReport {
SalesReport(this.totals);
final SalesTotals totals;
}
D: dependency inversion. Depend on abstractions; let something else choose the concrete class.
// Before: the service is welded to one gateway and one database file.
class OrderService {
final _payments = CardGateway(apiKey: Platform.environment['CARD_KEY']!);
final _repository = OrderRepository(Database.open('orders.db'));
}
// With Spring: the service names interfaces; the container picks the
// implementations (by profile, @Primary, a test override...).
@Service()
class OrderService {
OrderService(this.payments, this.repository);
final PaymentGateway payments;
final OrderRepository repository;
}
You can follow all five by hand, but every class then needs a factory, and the factories need wiring of their own. The container does that wiring, which makes the right design the easy one.
The idea
With Spring, a class declares what it needs in its constructor, and an annotation tells the container to manage it:
@Service()
class OrderService {
OrderService(this._repository, this._payments, this._mailer);
final OrderRepository _repository;
final PaymentGateway _payments;
final Mailer _mailer;
Future<void> place(Order order) async {
await _payments.charge(order.total);
await _repository.save(order);
await _mailer.send(order.email, 'Thank you for your order');
}
}
An object the container manages is a bean. The container is the application context. When the application starts, the context:
- finds every bean class (the generator lists them at build time);
- works out the order:
OrderServiceneeds anOrderRepository, aPaymentGatewayand aMailer, so those come first; - creates each bean once and passes it to every constructor that asks for its type;
- checks the whole graph first. A missing bean, two candidates for one parameter, or a cycle stop the start with a report.
***************************
APPLICATION FAILED TO START
***************************
Description:
Bean 'orderService' required a bean of type Mailer that could not be found (while creating orderService).
Action:
Declare a bean of that type (a @Component class or a @Bean method), check its @Profile / conditions, or make the injection point nullable.
OrderService no longer knows where its collaborators come from. It is the same plain class: a test can still call OrderService(fakeRepository, fakePayments, fakeMailer).
Declaring beans
An annotation on the class makes it a bean:
| Annotation | Use it for |
|---|---|
@Component() |
Any bean |
@Service() |
A service: business logic |
@Repository() |
Data access |
@Controller(), @RestController() |
Web controllers (with the web starter) |
@Configuration() |
A class whose @Bean() methods create beans |
@Service(), @Repository() and @Controller() behave like @Component(); the name only states the role. A bean is a singleton by default: one instance for the whole application, created at startup and shared.
@Repository()
class OrderRepository {
OrderRepository(this._database);
final Database _database;
Future<void> save(Order order) => _database.insert('orders', order.toRow());
}
More: @Component, @Service, @Repository, the container and beans.
Constructor injection
The container fills each constructor parameter by its type:
@Service()
class CheckoutService {
CheckoutService(
this.orders, // the one OrderService bean
this.listeners, // every OrderListener bean, in @Order
this.coupons, // nullable: null when there is no CouponService bean
);
final OrderService orders;
final List<OrderListener> listeners;
final CouponService? coupons;
}
- A
List<T>parameter gets every bean of typeT. - A nullable parameter is optional.
- An
ObjectProvider<T>parameter gets the bean later, or not at all (see ObjectProvider). @Lazy()on a parameter injects a generated proxy that looks the bean up when it is used, which also breaks a cycle (see @Lazy).
Constructor injection is the recommended form: the fields can be final, and the class can be built by hand in a test. Field injection with @Autowired() on a late field exists too (see @Autowired).
Interfaces and several implementations
Depending on an interface instead of a class is what makes swapping easy. When several beans implement it, tell the container which one to use.
abstract interface class PaymentGateway {
Future<void> charge(double amount);
}
// The real gateway, in every profile but dev.
@Component()
@Profile(['!dev'])
class CardGateway implements PaymentGateway {
CardGateway(@Value(r'${payments.card.key}') this._key);
final String _key;
@override
Future<void> charge(double amount) async {/* call the card provider with _key */}
}
// A fake for development: nothing is charged.
@Component()
@Profile(['dev'])
class FakeGateway implements PaymentGateway {
@override
Future<void> charge(double amount) async {}
}
With --spring.profiles.active=dev (or SPRING_PROFILES_ACTIVE=dev), OrderService gets the fake; otherwise the real one. The service does not change.
When both beans exist at once, choose:
| Tool | Effect |
|---|---|
@Primary() on a bean |
It wins when one bean of the type is asked for. |
@Fallback() on a bean |
It is used only when no other candidate exists. |
@Qualifier('name') on a bean and on a parameter |
The parameter gets the bean with that qualifier. |
| The parameter's name | When it matches a bean name, that bean is chosen. |
@Component()
@Primary()
class EmailNotifier implements Notifier { /* ... */ }
@Component()
@Qualifier('sms')
class SmsNotifier implements Notifier { /* ... */ }
@Service()
class Alerts {
Alerts(this.notifier, @Qualifier('sms') this.urgent);
final Notifier notifier; // EmailNotifier, the primary one
final Notifier urgent; // SmsNotifier
}
More: @Primary, @Qualifier, @Fallback, @Profile.
Patterns that extend themselves
With a container, the classic design patterns need no registration code. You add a class, and the container finds it. Nothing that already works is edited, which is the open/closed principle in practice.
Observer: every implementation is picked up
A service announces what happened, and any number of listeners react. Ask for a List of the interface, and the container passes every bean that implements it. A listener that must run before the others declares its place with the @Order annotation (lower values first):
abstract interface class OrderListener {
Future<void> onPlaced(Order order);
}
@Service()
class OrderService {
OrderService(this.repository, this.listeners);
final OrderRepository repository;
final List<OrderListener> listeners; // every OrderListener bean
Future<void> place(Order order) async {
await repository.save(order);
for (final listener in listeners) {
await listener.onPlaced(order);
}
}
}
@Component()
class ConfirmationMail implements OrderListener {
ConfirmationMail(this.mailer);
final Mailer mailer;
@override
Future<void> onPlaced(Order order) =>
mailer.send(order.email, 'Thank you for your order');
}
A loyalty bonus a month later is one new file. OrderService and ConfirmationMail are not touched:
@Component()
class LoyaltyBonus implements OrderListener {
LoyaltyBonus(this.points);
final PointsService points;
@override
Future<void> onPlaced(Order order) => points.add(order.customer, 10);
}
A listener only for some profiles (@Profile(['prod'])) or behind a setting (@ConditionalOnProperty) is still just a class: where its condition is false, it is not in the list.
For looser coupling, publish an event instead: the publisher does not even know an interface. Any bean method with @EventListener() receives the events of its parameter's type:
class OrderPlaced {
const OrderPlaced(this.order);
final Order order;
}
@Service()
class OrderService {
OrderService(this.repository, this.events);
final OrderRepository repository;
final ApplicationEventPublisher events;
Future<void> place(Order order) async {
await repository.save(order);
events.publishEvent(OrderPlaced(order));
}
}
@Component()
class SalesReport {
@EventListener()
void onPlaced(OrderPlaced event) { /* count the sale */ }
}
More: @EventListener, events.
Decorator: behaviour added around a bean
A decorator wraps an object to add behaviour without changing it. With a container, the wrapping is declared once, and every class that asks for the interface gets the decorated object.
One decorator for one interface. Mark the decorator @Primary, so it is the bean everyone receives, and let it ask for the real one by its qualifier:
@Component()
@Qualifier('card')
class CardGateway implements PaymentGateway { /* charges the card */ }
// Retries a failed charge up to three times.
@Component()
@Primary()
class RetryingGateway implements PaymentGateway {
RetryingGateway(@Qualifier('card') this._inner);
final PaymentGateway _inner;
@override
Future<void> charge(double amount) async {
for (var attempt = 1; ; attempt++) {
try {
return await _inner.charge(amount);
} on Exception {
if (attempt == 3) rethrow;
}
}
}
}
OrderService still asks for a PaymentGateway and now gets the retrying one. Removing the retries is deleting one class.
One behaviour for many classes. When the same thing should wrap many methods, such as timing, logging, caching or transactions, an aspect is the decorator. It is written once and applied by a rule, here to every method marked @Timed():
class Timed {
const Timed();
}
@Aspect()
@Component()
class TimingAspect {
@Around('@annotation(Timed)')
Object? time(ProceedingJoinPoint call) {
final watch = Stopwatch()..start();
try {
return call.proceed(); // the real method
} finally {
const SpringLog('timing')
.info('${call.signature.name}: ${watch.elapsedMilliseconds} ms');
}
}
}
@Service()
class ReportService {
@Timed()
Report monthly() { /* ... */ }
}
The generator writes the proxy classes that run the aspect at build time; ReportService itself contains no timing code. The cache and data starters work the same way: @Cacheable and @Transactional are aspects that the starters bring.
More: AOP, @Around and the other advice.
@Bean methods
Some objects are not your classes: a Random from dart:math, a client of another package, an object that needs a few lines to build. Create them in a @Bean() method of a @Configuration() class. The method's parameters are injected like a constructor's:
@Configuration()
class InfrastructureConfig {
@Bean()
Random random() => Random.secure();
@Bean()
Database database(@Value(r'${orders.db:orders.db}') String path) =>
Database.open(path);
// Mailer has a close() method: the container calls it when the context closes.
@Bean()
Mailer mailer(MailProperties properties) =>
Mailer(properties.host, port: properties.port);
}
The bean's name is the method's name (random, database, mailer). More: @Bean, @Configuration.
Configuration values
Settings live in lib/resources/application.properties or application.yml, with one file per profile on top (application-prod.yml). Environment variables and command-line arguments override the files, so the same build runs everywhere.
# lib/resources/application.yml
mail:
host: smtp.example.com
port: 587
orders:
limit: 50
One value goes into a parameter with @Value:
@Service()
class OrderLimits {
// 50 from the file; 100 when the key is missing.
OrderLimits(@Value(r'${orders.limit:100}') this.limit);
final int limit;
}
A group of values goes into a typed class with @ConfigurationProperties. The class is a bean, bound from every key under the prefix, converted to the field types and, with @Validated(), checked at startup:
@ConfigurationProperties('mail')
@Validated()
class MailProperties {
/// The SMTP server.
@NotBlank()
String host = 'localhost';
@Min(1)
int port = 25;
Duration timeout = const Duration(seconds: 10); // mail.timeout=30s
}
port is bound from mail.port, --mail.port=2525 or MAIL_PORT=2525. An invalid value stops the start with the key, the value and the rule it breaks. More: Configuration, @Value, @ConfigurationProperties, Profiles.
Lifecycle
The container creates beans, and it also closes them. A bean can run code at both ends:
@Component()
class PriceCache {
PriceCache(this._source);
final PriceSource _source;
final _prices = <String, double>{};
// After the constructor and the injection, before anyone uses the bean.
@PostConstruct()
void warmUp() => _prices.addAll(_source.defaults());
// When the context closes: at shutdown, or at the end of a test.
@PreDestroy()
void clear() => _prices.clear();
}
For background work that starts and stops with the application (a poller, a socket), implement Lifecycle or SmartLifecycle. More: @PostConstruct, @PreDestroy, Lifecycle and SmartLifecycle.
Scopes
A singleton is right for most beans. @Scope changes how many instances exist:
| Scope | Instances |
|---|---|
| singleton (the default) | One for the whole context |
ScopeType.prototype |
A new one for every injection and every lookup |
| a custom scope | One per span you define: a screen, a session, a job. The Flutter navigation starter registers scopes per route, for example. |
// Each user of a cart gets their own instance.
@Component()
@Scope(ScopeType.prototype)
class ShoppingCart {
final items = <String>[];
}
More: @Scope.
Testing
Because a bean receives its dependencies, tests are simple at both levels.
A unit test builds the class by hand, with fakes:
test('a placed order is charged and saved', () async {
final payments = RecordingGateway();
final service = OrderService(InMemoryOrders(), payments, SilentMailer());
await service.place(Order(total: 12.5, email: '[email protected]'));
expect(payments.charged, [12.5]);
});
An application test starts the real application, with the test's properties and profiles, and replaces only the beans you name. springBootTest comes from spring_boot_starter_test:
import 'package:spring_boot_starter_test/spring_boot_starter_test.dart';
import 'package:test/test.dart';
import '../bin/spring_gen/main.spring.dart'; // the generated springApplication
void main() {
final payments = RecordingGateway();
final app = springBootTest(
springApplication,
profiles: ['test'], // reads application-test.properties
properties: {'orders.limit': '3'},
overrides: [BeanOverride<PaymentGateway>(payments)],
);
test('the checkout uses the fake gateway', () async {
await app.getBean<OrderService>().place(Order(total: 5, email: '[email protected]'));
expect(payments.charged, [5]);
});
}
Every bean that asks for a PaymentGateway gets the fake; the rest of the application is real. More: Tests: @SpringBootTest and @DataTest.
Without Spring Boot
The container works on its own too. A @ComponentScan() variable collects the beans of its directory, and you start the context yourself:
// lib/src/beans.dart
import 'package:spring_core_dart/spring_core_dart.dart';
import 'package:my_app/spring_gen/src/beans.spring.dart'; // written by the generator
@ComponentScan()
final BeanModule appBeans = $appBeans;
void main() {
final context = ApplicationContext.run([appBeans]);
context.getBean<OrderService>();
context.close();
}
@SpringBootApplication() does this for you, and adds the configuration files, the starters and the start-up report. More: @ComponentScan, ApplicationContext.
In Spring (Java)
The model is Spring's, with the same names: @Component, @Service, @Bean, @Primary, @Qualifier, @Value, @ConfigurationProperties, @PostConstruct, @Scope. Differences that matter here:
- The beans are found by the generator at build time, not by scanning the class path at startup.
- A bean cycle is always an error. Break it with
@Lazy()on a parameter or anObjectProvider. - Placeholders are written in raw strings:
@Value(r'${key}').
See also
- Comparisons: get_it, Observer, logic around a method and HTTP clients, side by side
- The container and beans
- Configuration
- Conditions