一. 回顾

前面学习了Day42——定制错误数据,今天学习嵌入式的Servlet容器配置

二. 嵌入式的Servlet容器配置

2.1 什么是嵌入式的Servlet容器

Servlet容器:比如Tomcat
嵌入式:无需在本地电脑安装Servlet容器,SpringBoot即可成功启动访问web页面

2.2 如何定制和修改Servlet容器的相关配置

既然SpringBoot将Servlet容器嵌入了, 那如何定制以及修改Servlet容器的相关配置呢?

2.2.1 方法一

0基础入门SpringBoot时,有配置过Servlet容器设置,如下:

#通用的servlet容器设置
#server.xxx
#tomcat的设置
#server.tomcat.xxx

#配置项目访问路径(配置属性的类是ServerProperties)
server.servlet.context-path=/crud
server.port=8081
#配置tomcat相关的设置
server.tomcat.uri-encoding=utf-8

2.2.2 方法二

编写一个WebServerFactoryCustomizer(原本SpringBoot1.x版本是编写EmbeddedServletContainerCustomizer,SpringBoot2.x版本已经没有这个类了,改为使用WebServerFactoryCustomizer)。

代码如下:

@Configuration
//@EnableWebMvc
public class MyMvcConfig2 implements WebMvcConfigurer {

    //配置一个嵌入式的Servlet容器定制器(SpringBoot2.x版本以上讲EmbeddedServletContainerCustomizer替换了)
    @Bean
    public WebServerFactoryCustomizer embeddedWebServerFactoryCustomizerAutoConfiguration(){
        return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>(){
            //定制嵌入式Servlet容器的相关规则
            @Override
            public void customize(ConfigurableWebServerFactory factory) {
                factory.setPort(8083);
            }
        };
    }
}

总结:在SpringBoot中会编写很多xxxCustomizer帮助我们定制配置

Logo

openvela 操作系统专为 AIoT 领域量身定制,以轻量化、标准兼容、安全性和高度可扩展性为核心特点。openvela 以其卓越的技术优势,已成为众多物联网设备和 AI 硬件的技术首选,涵盖了智能手表、运动手环、智能音箱、耳机、智能家居设备以及机器人等多个领域。

更多推荐