Skip to content

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.

Create a project named “bean-guide”:

Terminal window
manul new bean-guide

Create a source file containing the bean:

src/echo-service.mnl
@Bean
class EchoService {
fn echo(message: string) -> string {
return message
}
}

Deploy the code:

Terminal window
manul deploy

Test the bean with an HTTP request:

POST /bean-guide/echo-service/echo
{
"message": "Hi"
}

Response:

HTTP/1.1 200 OK
Hi

Request 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.

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:

src/user-service.mnl
@Bean
class NotificationService {
fn notify(message: string) {
print("Message: " + message)
}
}
@Bean
class UserService(
notificationService: NotificationService
) {
fn createUser(name: string) {
// User creation logic omitted
notificationService.notify("User " + name + " created.")
}
}

A bean directly depending on the class of another bean is called tight coupling.

To decouple, we use interfaces:

src/user-service.mnl
interface INotificationService {
fn notify(message: string)
}
@Bean
class NotificationService implements INotificationService {
fn notify(message: string) {
print("Message: " + message)
}
}
@Bean
class UserService(
notificationService: NotificationService
notificationService: INotificationService
) {
fn createUser(name: string) {
// User creation logic omitted
notificationService.notify("User " + name + " created.")
}
}