官术网_书友最值得收藏!

Understanding the component scan

Let's go back to our example that we created previously:

package com.microservices.chapter2

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.ResponseBody

@SpringBootApplication
class Chapter2Application

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

主站蜘蛛池模板: 天长市| 托克托县| 鸡泽县| 上饶市| 聂拉木县| 南投县| 墨竹工卡县| 伊金霍洛旗| 嵊州市| 华亭县| 左权县| 军事| 眉山市| 电白县| 临清市| 偏关县| 乡城县| 岱山县| 右玉县| 白河县| 乌兰察布市| 德庆县| 恭城| 贞丰县| 宁德市| 炉霍县| 法库县| 江陵县| 罗源县| 葵青区| 东宁县| 宜城市| 县级市| 旬阳县| 牟定县| 黔东| 凌源市| 金华市| 张家川| 拜城县| 神木县|