虽然Spring Boot默认嵌入了Tomcat作为容器,但是并不代表我们只能使用Tomcat作为服务容器。Spring Boot提供我们即时即用的starts,所以我们也可以使用Jetty和Undertow。
如果我们想要使用Jetty作为服务容器,我们老板娘添加Jetty的Starter。
3.4.1代码实现
- Tomcat是Spring Boot默认的服务容器,所以我们现在需要将Tomcat移除掉。在build.gradle文件中加入下面代码:
configurations { |
2.在build.gradel中加入Jetty的依赖包。
implementation 'org.springframework.boot:spring-boot-starter-jetty'
3.项目中出现错误,我们需要移除掉在WebConfiguration类中的RemoteIpFilter.
4.启动项目,你将会看到。
2020-04-05 10:02:00.336 INFO 15008 --- [ main] org.eclipse.jetty.util.log : Logging initialized @4644ms to org.eclipse.jetty.util.log.Slf4jLog 2020-04-05 10:02:01.323 INFO 15008 --- [ main] o.s.b.w.e.j.JettyServletWebServerFactory : Server initialized with port: 8080 2020-04-05 10:02:01.334 INFO 15008 --- [ main] org.eclipse.jetty.server.Server : jetty-9.4.27.v20200227; built: 2020-02-27T18:37:21.340Z; git: a304fd9f351f337e7c0e2a7c28878dd53614 |
3.4.2代码说明
我们移除掉Tomcat所依赖的包之后,我们引入的了Jetty的包,这样的话中,Spring Boot 启动时会去扫描选择使用哪个服务容器
如果我们深入看EmbeddedServletContainerAutoConfiguration的类,我们将会看到这几个代码Servlet.class,Server.class和Loader.class。这些代码是来自于Jetty的包。
/** |
@ConditionalOnClass注释告诉Spring Boot 如果g.eclipse.jetty.server.Server和org.eclipse.jetty.util.Loader出现在包路径下,则使用仅仅一个EmbeddedJetty的配置。