目标
既然是minimal web server,就努力做到最小,这样才有助于理解how it works inside Spring Boot.
要点
POM dependency、autoconfigure
0. 环境: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);
}
}
上面的代码比我其他见过的示例代码,甚至官网上的代码都要少,呵呵。
运行:直接Run,不需要Run As Spring Boot App. 结果如下:

看上去这是一个错误提示,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
官网的解释: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.
事实上,如果想把上面的代码变得更小一些,去掉这两行,web server是不会起来的,在浏览器输入http://localhost:8080会得到如下结果:

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时会出现错误:
Exception encountered during context initialization - cancelling refresh attempt
问题
1. 找不到"/"的URL mapping时,显示Whitelabel Error Page,可以在后续的代码深入学习时关注一下。