@Controller

Create controllers with @Path and @Controller.

Controller

The javalin-generator (APT processor) detects classes with @Controller and generates source code for mapping web routes to the controller method.

Path

@Path("/contacts") provides the path segment that is prepended to any path segments defined by @Get, @Post etc.

@Controller
@Path("/contacts")
class ContactController {

  private final MyService myService;

  @Inject
  ContactController(MyService myService) {
    this.myService = myService;
  }

  @Get("/:id")
  Contact getById(long id) {
    ...
  }

  @Post
  void save(Contact contact) {
    ...
  }

  ...
}

The controllers can have dependencies injected.

Testing

One of the big motivations of having these controllers is to help with testing.

When testing the ContactController:

  • We can create ContactController instances with mock/test doubles for it's dependencies (MyService)
  • We can largely test the methods without any web context/request/response objects