PostConstruct constructor
const
PostConstruct()
Marks a method to be invoked after 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
orFuture<void>
. - Only applied to methods (not classes or fields).
Example — Synchronous Initialization
@Service()
class CacheManager {
late final Cache _cache;
@Autowired()
late final DataSource dataSource;
@PostConstruct()
void init() {
print("Initializing cache from database...");
_cache = Cache.loadFrom(dataSource);
}
}
Example — Asynchronous Initialization
@Service()
class WorkerPool {
final _workers = <Worker>[];
@PostConstruct()
Future<void> startWorkers() async {
for (var i = 0; i < 4; i++) {
final worker = Worker();
await worker.start();
_workers.add(worker);
}
}
}
Implementation
const PostConstruct();