1. 程式人生 > >springboot 嵌入式 tomcat自定義配置

springboot 嵌入式 tomcat自定義配置

springboot內建了tomcat,如果我們有自定義需求該怎麼做呢?

配置EmbeddedServletContainerFactory

  @Bean
    public EmbeddedServletContainerFactory embeddedServletContainerFactory() {
        TomcatEmbeddedServletContainerFactory embeddedServletContainerFactory = new TomcatEmbeddedServletContainerFactory();
        embeddedServletContainerFactory.setPort(80
); embeddedServletContainerFactory.setDisplayName("嵌入式tomcat測試"); embeddedServletContainerFactory.setSessionTimeout(30, TimeUnit.SECONDS); return embeddedServletContainerFactory; }

通過分析 EmbeddedWebApplicationContext 類得知:

    private void createEmbeddedServletContainer
() { EmbeddedServletContainer localContainer = this.embeddedServletContainer; ServletContext localServletContext = getServletContext(); if (localContainer == null && localServletContext == null) { EmbeddedServletContainerFactory containerFactory = getEmbeddedServletContainerFactory(); this
.embeddedServletContainer = containerFactory .getEmbeddedServletContainer(getSelfInitializer()); } else if (localServletContext != null) { try { getSelfInitializer().onStartup(localServletContext); } catch (ServletException ex) { throw new ApplicationContextException("Cannot initialize servlet context", ex); } } initPropertySources(); }

springboot 會通過EmbeddedServletContainerFactory類來建立servlet容器,所以我們可以配置該Bean來達到自定義的效果,需要注意的是,通過該類自定義的配置會被自定義的配置所覆蓋,列如application.properties 裡的引數可以覆蓋這裡的配置

配置 EmbeddedServletContainerCustomizer

    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer(ConfigurableEmbeddedServletContainer configurableEmbeddedServletContainer) {
        return new EmbeddedServletContainerCustomizer(){
            public void customize(ConfigurableEmbeddedServletContainer container) {
                container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error/500"));
                container.addErrorPages(new ErrorPage(HttpStatus.BAD_GATEWAY, "/error/500"));
                container.setDisplayName("ABC");
                container.setPort(9999);
            }
        };
    }

springboot裡面有這樣一個類
EmbeddedServletContainerCustomizerBeanPostProcessor,
檢視該類繼承層次
public class EmbeddedServletContainerCustomizerBeanPostProcessor
implements BeanPostProcessor, ApplicationContextAware,再看看下面這個方法

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        if (bean instanceof ConfigurableEmbeddedServletContainer) {
            postProcessBeforeInitialization((ConfigurableEmbeddedServletContainer) bean);
        }
        return bean;
    }

由此得知,springboot會在servlet容器初始化時通過EmbeddedServletContainerCustomizerBeanPostProcessor類對容器做自定義修改,值得注意的是,這裡的修改不會被配置檔案裡的配置所覆蓋