Spring Boot中以代码方式配置Tomcat

白昼怎懂夜的黑 提交于 2019-12-04 15:41:35

在Spring Boot2.0以上配置嵌入式Servlet容器时EmbeddedServletContainerCustomizer类不存在,经网络查询发现被WebServerFactoryCustomizer替代.

Spring Boot 1.0中:

通用配置举例

@Component
    public static class CustomServletContainer implements EmbeddedServletContainerCustomizer{
     @Override
        public void customize(ConfigurableEmbeddedServletContainer container) {
            container.setPort(8888);//配置端口
            container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"));//配置错误页面
            container.setSessionTimeout(10,TimeUnit.MINUTES);//配置用户会话过期时间
        }
     
    }

特定配置举例

以Tomcat为例。
 @Bean
    public EmbeddedServletContainerFactory servletContainer() {
        TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
        factory.setPort(8888);
        factory.setSessionTimeout(10, TimeUnit.MINUTES);
        factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"));
        return factory;
    }

在springboot2.0之后

@FunctionalInterface
public interface WebServerFactoryCustomizer<T extends WebServerFactory> {
    void customize(T factory);
}

 

package springboot.configure;

import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
@Component
public class CustomServletContainer implements WebServerFactoryCustomizer<ConfigurableWebServerFactory>{
@Override
    public void customize(ConfigurableWebServerFactory factory) {
        factory.setPort(8888);
        factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,"/404.html"));
    }

}

 

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!