Beans
A bean is an object that is initiated, assembled and managed by the runtime. The primary goal is dependency injection. Instead of the class being responsible for looking up its dependencies, the runtime injects them.
Bean Definition
Section titled “Bean Definition”Create a project named “bean-guide”:
manul new bean-guideCreate a source file containing the bean:
@Beanclass EchoService {
fn echo(message: string) -> string { return message }
}Deploy the code:
manul deployTest the bean with an HTTP request:
POST /bean-guide/echo-service/echo
{ "message": "Hi"}Response:
HTTP/1.1 200 OK
HiRequest Path
The request path for a bean method is:
/{project-name}/{hyphenated-bean-name}/{hyphenated-method-name}
project-name: “bean-guide” in this example.hyphenated-bean-name: The bean name converted to hyphenated form.hyphenated-method-name: The method name converted to hyphenated form.
Dependency Injection
Section titled “Dependency Injection”A bean declares its dependencies using the constructor parameters. The runtime will automatically find the depended beans and pass them to the constructor.
Here is an example involving two beans, with one depending on the other:
@Beanclass NotificationService {
fn notify(message: string) { print("Message: " + message) }
}
@Beanclass UserService( notificationService: NotificationService) {
fn createUser(name: string) { // User creation logic omitted notificationService.notify("User " + name + " created.") }
}Using Interface
Section titled “Using Interface”A bean directly depending on the class of another bean is called tight coupling.
To decouple, we use interfaces:
interface INotificationService {
fn notify(message: string)
}
@Beanclass NotificationService implements INotificationService {
fn notify(message: string) { print("Message: " + message) }
}
@Beanclass UserService( notificationService: NotificationService notificationService: INotificationService) {
fn createUser(name: string) { // User creation logic omitted notificationService.notify("User " + name + " created.") }
}