SpringBoot | 跟随官网的脚步 | 105: Minimal Web Server

目标

既然是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,可以在后续的代码深入学习时关注一下。

参考

官网 | getting-started-first-application

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,167评论 0 10
  • 看过多少作者细数曾经,被喷了一脸甜蜜最后只说一句谢谢曾经。既然都爱了,为什么就不能再深情一点?既然都决定了,为什么...
    欧式姑娘阅读 3,325评论 0 4
  • 哦哦,我又来光顾你喽! 找个借口我想我就会来的,原因很简单啊,那就是你的——你的——你的魅力所在哦! 从黄昏到夜幕~嗯~
    麸子存世阅读 482评论 0 0
  • 昵称:霖仔 地点:广东揭阳 职业:学生 照片: 自荐文章: 其实没有能拿得出手的。 《黑夜中重生》目录(未完结) ...
    墨存啊阅读 2,934评论 2 4

友情链接更多精彩内容