PreConstruct constructor

const PreConstruct()

Marks a method to be invoked before a pod has been fully constructed and its dependencies injected, but before it is made available for use in the context.

This is typically used for:

  • Initialization logic that depends on injected fields.
  • Validating configuration.
  • Opening resources (like database connections).

Rules

  • Must be a no-arg method.
  • Return type should be void or Future<void>.
  • Only applied to methods (not classes or fields).

Example — Synchronous Initialization

@Service()
class CacheManager {
  final _cache = <String, String>{};

  void put(String key, String value) => _cache[key] = value;

  @PreConstruct()
  void init() {
    print("Initializing cache from database...");
    _cache = Cache.loadFrom(dataSource);
  }
}

Example — Asynchronous Initialization

@Service()
class WorkerPool {
  final _workers = <Worker>[];

  @PreConstruct()
  Future<void> initWorkers() async {
    for (final worker in _workers) {
      await worker.start();
    }
  }
}

Implementation

const PreConstruct();