@Controller class FirstController(val exampleService: ExampleService) { @RequestMapping(value = "/user/{name}", method = arrayOf(RequestMethod.GET)) @ResponseBody fun hello(@PathVariable name: String) = exampleService.getHello(name) }
fun main(args: Array<String>) { runApplication<Chapter2Application>(*args) }
We add a controller class, then when our application starts we can see in the log:
RequestMappingHandlerMapping : Mapped "{[/user/{name}],methods=[GET]}" onto public java.lang.String com.microservices.chapter2.FirstController.hello(java.lang.String)
How has the application found our controller and wired into a request mapping?
When the Spring Boot application starts, it will scan all the classes and packages underneath the application context class recursively, and if any class is annotated as a component it will create an instance of it and add it to the Spring Boot application context. This feature is named as the component scan.
Spring Components instances are named beans, so basically we can say that our context is a collection of beans.
Later on, when the Spring Boot application starts, if it's a web application, it will get any class annotated with @Controller that is on the context and create a mapping that will get the request coming to our microservice to that class.