Create a Logger component with a name field and a log method.
← Dependency Injection · Ref: Q1105
Define a component with fields and methods:
defines component Logger name <- "DefaultLogger" log() -> message as String <- output as String: name + ": " + message
Components are DI-managed types with fields, constructors, methods, and operators.
See Q227 for compile-time DI validation. See Q1110 for register and inject.
Example
defines module qa.di.definecomponent defines component Logger name <- "AppLogger" getName() <- rtn as String: name log() -> message as String <- output as String: `${name}: ${message}` default operator defines program DefineComponentDemo() stdout <- Stdout() logger <- Logger() result <- logger.log("Application started") stdout.println(result) stdout.println(`Logger name: ${logger.getName()}`)
Common mistakes
E01010 — EK9 has no annotations. Use 'defines component' to declare DI-managed types.
Incorrect:
defines class @Component Logger
Correct:
defines component Logger
Other ways to ask this
- I need to define a reusable service component with fields and methods
- In Spring I'd use @Component on a class. Write the EK9 equivalent
- Given a logging service, define it as a component with state and behaviour
- Build a basic component that holds configuration and provides a method
Coming from another language?
Spring: @Component class. Guice: bind(Logger.class). .NET: services.AddSingleton<Logger>(). EK9: defines component + register in application.
Keywords: define, component, fields, methods, service, DI