目標(biāo)
既然是minimal web server,就努力做到最小,這樣才有助于理解how it works inside Spring Boot.
要點(diǎn)
POM dependency、autoconfigure
0. 環(huán)境:JDK + eclipse, 不需要STS
1. Create a new Maven project:
? 如果需要,在Select project name and location勾選Create a simple project(skip archetype selection)
? ? Group Id: com.example
? ? Artifact Id: springdemo-101
2. POM, add dependency
????Group Id: org.springframework.boot? ??
????Artifact Id: spring-boot-starter-web
? ? Version: 2.0.0.RELEASE
3. Java, add a class example?
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
@EnableAutoConfiguration
public class example {
????public static void main(String args[]) throws Exception{
????????SpringApplication.run(example.class, args);
????}
}
上面的代碼比我其他見過的示例代碼,甚至官網(wǎng)上的代碼都要少,呵呵。
運(yùn)行:直接Run,不需要Run As Spring Boot App. 結(jié)果如下:
看上去這是一個(gè)錯(cuò)誤提示,but actually it means that the web Server is up -- someone is listening at port 8080 and respond to you via HTTP protocol, though it does not understand what to do in response to the request "GET /" !
分析
1. 為什么需要autoconfigure, 即下面兩行代碼
import org.springframework.boot.autoconfigure.*;
@EnableAutoConfiguration
官網(wǎng)的解釋:The second class-level annotation is?@EnableAutoConfiguration. This annotation tells Spring Boot to “guess” how you want to configure Spring, based on the jar dependencies that you have added. Since?spring-boot-starter-web?added Tomcat and Spring MVC, the auto-configuration assumes that you are developing a web application and sets up Spring accordingly.
事實(shí)上,如果想把上面的代碼變得更小一些,去掉這兩行,web server是不會(huì)起來的,在瀏覽器輸入http://localhost:8080會(huì)得到如下結(jié)果:
2. 日志分析
日志大概分為以下幾部分:
Spring Banner
Staring example?
ConfigServletWebServerApplicationContext
Tomcat
Spring embedded WebApplicationContext
Servlet dispatcherServlet mapped to [/]
Mapping filter
Mapped
Registering beans for JMX exposure on startup
Tomcat started on port(s): 8080 (http) with context path ''
Started example in 2.528 seconds (JVM running for 3.104)
如果沒有前面autoconfigure的兩條語句,在ConfigServletWebServerApplicationContext時(shí)會(huì)出現(xiàn)錯(cuò)誤:
Exception encountered during context initialization - cancelling refresh attempt
問題
1. 找不到"/"的URL mapping時(shí),顯示W(wǎng)hitelabel Error Page,可以在后續(xù)的代碼深入學(xué)習(xí)時(shí)關(guān)注一下。