您好,登錄后才能下訂單哦!
小編給大家分享一下SpringBoot配置嵌入式Servlet容器和外置Servlet容器的使用方法,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
配置嵌入式Servlet容器
SpringBoot默認使用Tomcat作為嵌入式的Servlet容器;
問題?
1)、如何定制和修改Servlet容器的相關配置;
1、修改和server有關的配置(ServerProperties【也是EmbeddedServletContainerCustomizer】);
server.port=8081 server.context-path=/crud server.tomcat.uri-encoding=UTF-8 //通用的Servlet容器設置 server.xxx //Tomcat的設置 server.tomcat.xxx
2、編寫一個EmbeddedServletContainerCustomizer:嵌入式的Servlet容器的定制器;來修改Servlet容器的配置(1.x)
在Spring Boot2.0以上配置嵌入式Servlet容器時EmbeddedServletContainerCustomizer類不存在,被WebServerFactoryCustomizer替代。
1.x
@Bean //一定要將這個定制器加入到容器中 public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer(){ return new WebServerFactoryCustomizer<ConfigurableWebServerFactory> { //定制嵌入式的Servlet容器相關的規則 @Override public void customize(ConfigurableWebServerFactory factory) { container.setPort(8083); } }; }
2.x
@Bean //一定要將這個定制器加入到容器中 public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer(){ return new EmbeddedServletContainerCustomizer() { //定制嵌入式的Servlet容器相關的規則 @Override public void customize(ConfigurableEmbeddedServletContainer container) { container.setPort(8083); } }; }
2)、注冊Servlet三大組件【Servlet、Filter、Listener】
由于SpringBoot默認是以jar包的方式啟動嵌入式的Servlet容器來啟動SpringBoot的web應用,沒有web.xml文件。
注冊三大組件用以下方式
ServletRegistrationBean
//注冊三大組件 @Bean public ServletRegistrationBean myServlet(){ ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet"); return registrationBean; }
FilterRegistrationBean
@Bean public FilterRegistrationBean myFilter(){ FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(new MyFilter()); registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet")); return registrationBean; }
ServletListenerRegistrationBean
@Bean public ServletListenerRegistrationBean myListener(){ ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener()); return registrationBean; }
SpringBoot幫我們自動SpringMVC的時候,自動的注冊SpringMVC的前端控制器;DIspatcherServlet;
DispatcherServletAutoConfiguration中:
@Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME) @ConditionalOnBean(value = DispatcherServlet.class, name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME) public ServletRegistrationBean dispatcherServletRegistration( DispatcherServlet dispatcherServlet) { ServletRegistrationBean registration = new ServletRegistrationBean( dispatcherServlet, this.serverProperties.getServletMapping()); //默認攔截: / 所有請求;包靜態資源,但是不攔截jsp請求; /*會攔截jsp //可以通過server.servletPath來修改SpringMVC前端控制器默認攔截的請求路徑 registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME); registration.setLoadOnStartup( this.webMvcProperties.getServlet().getLoadOnStartup()); if (this.multipartConfig != null) { registration.setMultipartConfig(this.multipartConfig); } return registration; }
2)、SpringBoot能不能支持其他的Servlet容器;
3)、替換為其他嵌入式Servlet容器
默認支持:
Tomcat(默認使用)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> 引入web模塊默認就是使用嵌入式的Tomcat作為Servlet容器; </dependency>
Jetty
<!-- 引入web模塊 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <artifactId>spring-boot-starter-tomcat</artifactId> <groupId>org.springframework.boot</groupId> </exclusion> </exclusions> </dependency> <!--引入其他的Servlet容器--> <dependency> <artifactId>spring-boot-starter-jetty</artifactId> <groupId>org.springframework.boot</groupId> </dependency>
Undertow
<!-- 引入web模塊 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <artifactId>spring-boot-starter-tomcat</artifactId> <groupId>org.springframework.boot</groupId> </exclusion> </exclusions> </dependency> <!--引入其他的Servlet容器--> <dependency> <artifactId>spring-boot-starter-undertow</artifactId> <groupId>org.springframework.boot</groupId> </dependency>
4)、嵌入式Servlet容器自動配置原理;
SpringBoot2.X原理略有不同
由EmbeddedWebServerFactoryCustomizerAutoConfiguration(嵌入式web服務工廠定制器自動配置類)而不是EmbeddedServletContainerAutoConfiguration(嵌入式的Servlet容器自動配置),根據導入的依賴信息,該配置類會自動創建相應類型的容器工廠定制器(目前Spring Boot 2.x 版本支持tomcat、jetty、undertow、netty),以tomcat為例,這里會創建TomcatWebServerFactoryCustomizer組件:
@Configuration(proxyBeanMethods = false) @ConditionalOnWebApplication //指定類ServerProperties(Servlet容器相關的配置類)中的ConfigurationProperties功能,將配置文件中對應的屬性值與配置類中的屬性值進行映射,并將該配置類添加到IOC容器中 @EnableConfigurationProperties(ServerProperties.class) public class EmbeddedWebServerFactoryCustomizerAutoConfiguration { /** * Nested configuration if Tomcat is being used. */ @Configuration(proxyBeanMethods = false) //導入的Servlet依賴為Tomcat,則創建Tomcat web服務工廠定制器 @ConditionalOnClass({ Tomcat.class, UpgradeProtocol.class }) public static class TomcatWebServerFactoryCustomizerConfiguration { @Bean public TomcatWebServerFactoryCustomizer tomcatWebServerFactoryCustomizer(Environment environment,ServerProperties serverProperties) { return new TomcatWebServerFactoryCustomizer(environment, serverProperties); } } ... }
1.X中通過EmbeddedServletContainerAutoConfiguration:嵌入式的Servlet容器自動配置類創建組件
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) @Configuration @ConditionalOnWebApplication @Import(BeanPostProcessorsRegistrar.class) //導入BeanPostProcessorsRegistrar:Spring注解版;給容器中導入一些組件 //導入了EmbeddedServletContainerCustomizerBeanPostProcessor: //后置處理器:bean初始化前后(創建完對象,還沒賦值賦值)執行初始化工作 public class EmbeddedServletContainerAutoConfiguration { @Configuration @ConditionalOnClass({ Servlet.class, Tomcat.class })//判斷當前是否引入了Tomcat依賴; @ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT)//判斷當前容器沒有用戶自己定義EmbeddedServletContainerFactory:嵌入式的Servlet容器工廠;作用:創建嵌入式的Servlet容器 public static class EmbeddedTomcat { @Bean public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() { return new TomcatEmbeddedServletContainerFactory(); } } /** * Nested configuration if Jetty is being used. */ @Configuration @ConditionalOnClass({ Servlet.class, Server.class, Loader.class, WebAppContext.class }) @ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT) public static class EmbeddedJetty { @Bean public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory() { return new JettyEmbeddedServletContainerFactory(); } } /** * Nested configuration if Undertow is being used. */ @Configuration @ConditionalOnClass({ Servlet.class, Undertow.class, SslClientAuthMode.class }) @ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT) public static class EmbeddedUndertow { @Bean public UndertowEmbeddedServletContainerFactory undertowEmbeddedServletContainerFactory() { return new UndertowEmbeddedServletContainerFactory(); } }
1)、EmbeddedServletContainerFactory(嵌入式Servlet容器工廠)
public interface EmbeddedServletContainerFactory { //獲取嵌入式的Servlet容器 EmbeddedServletContainer getEmbeddedServletContainer( ServletContextInitializer... initializers); }
2)、EmbeddedServletContainer:(嵌入式的Servlet容器)
3)、以TomcatEmbeddedServletContainerFactory為例
@Override public EmbeddedServletContainer getEmbeddedServletContainer( ServletContextInitializer... initializers) { //創建一個Tomcat Tomcat tomcat = new Tomcat(); //配置Tomcat的基本環節 File baseDir = (this.baseDirectory != null ? this.baseDirectory : createTempDir("tomcat")); tomcat.setBaseDir(baseDir.getAbsolutePath()); Connector connector = new Connector(this.protocol); tomcat.getService().addConnector(connector); customizeConnector(connector); tomcat.setConnector(connector); tomcat.getHost().setAutoDeploy(false); configureEngine(tomcat.getEngine()); for (Connector additionalConnector : this.additionalTomcatConnectors) { tomcat.getService().addConnector(additionalConnector); } prepareContext(tomcat.getHost(), initializers); //將配置好的Tomcat傳入進去,返回一個EmbeddedServletContainer;并且啟動Tomcat服務器 return getTomcatEmbeddedServletContainer(tomcat); }
4)、我們對嵌入式容器的配置修改是怎么生效?
ServerProperties、EmbeddedServletContainerCustomizer
EmbeddedServletContainerCustomizer:定制器幫我們修改了Servlet容器的配置?
怎么修改的原理?
5)、容器中導入了EmbeddedServletContainerCustomizerBeanPostProcessor
//初始化之前 @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { //如果當前初始化的是一個ConfigurableEmbeddedServletContainer類型的組件 if (bean instanceof ConfigurableEmbeddedServletContainer) { // postProcessBeforeInitialization((ConfigurableEmbeddedServletContainer) bean); } return bean; } private void postProcessBeforeInitialization( ConfigurableEmbeddedServletContainer bean) { //獲取所有的定制器,調用每一個定制器的customize方法來給Servlet容器進行屬性賦值; for (EmbeddedServletContainerCustomizer customizer : getCustomizers()) { customizer.customize(bean); } } private Collection<EmbeddedServletContainerCustomizer> getCustomizers() { if (this.customizers == null) { // Look up does not include the parent context this.customizers = new ArrayList<EmbeddedServletContainerCustomizer>( this.beanFactory //從容器中獲取所有這葛類型的組件:EmbeddedServletContainerCustomizer //定制Servlet容器,給容器中可以添加一個EmbeddedServletContainerCustomizer類型的組件 .getBeansOfType(EmbeddedServletContainerCustomizer.class, false, false) .values()); Collections.sort(this.customizers, AnnotationAwareOrderComparator.INSTANCE); this.customizers = Collections.unmodifiableList(this.customizers); } return this.customizers; } ServerProperties也是定制器
步驟:
1)、SpringBoot根據導入的依賴情況,給容器中添加相應的EmbeddedServletContainerFactory【TomcatEmbeddedServletContainerFactory】
2)、容器中某個組件要創建對象就會驚動后置處理器;EmbeddedServletContainerCustomizerBeanPostProcessor;
只要是嵌入式的Servlet容器工廠,后置處理器就工作;
3)、后置處理器,從容器中獲取所有的EmbeddedServletContainerCustomizer,調用定制器的定制方法
5)、嵌入式Servlet容器啟動原理;
什么時候創建嵌入式的Servlet容器工廠?什么時候獲取嵌入式的Servlet容器并啟動Tomcat;
獲取嵌入式的Servlet容器工廠:
1)、SpringBoot應用啟動運行run方法
2)、refreshContext(context);SpringBoot刷新IOC容器【創建IOC容器對象,并初始化容器,創建容器中的每一個組件】;如果是web應用創建AnnotationConfigEmbeddedWebApplicationContext,否則:AnnotationConfigApplicationContext
3)、refresh(context);刷新剛才創建好的ioc容器;
public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. prepareRefresh(); // Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory); // Initialize message source for this context. initMessageSource(); // Initialize event multicaster for this context. initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. onRefresh(); // Check for listener beans and register them. registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
4)、 onRefresh(); web的ioc容器重寫了onRefresh方法
5)、webioc容器會創建嵌入式的Servlet容器;createEmbeddedServletContainer();
6)、獲取嵌入式的Servlet容器工廠:
EmbeddedServletContainerFactory containerFactory = getEmbeddedServletContainerFactory();
​從ioc容器中獲取EmbeddedServletContainerFactory 組件;TomcatEmbeddedServletContainerFactory創建對象,后置處理器一看是這個對象,就獲取所有的定制器來先定制Servlet容器的相關配置;
7)、使用容器工廠獲取嵌入式的Servlet容器:this.embeddedServletContainer = containerFactory .getEmbeddedServletContainer(getSelfInitializer());
8)、嵌入式的Servlet容器創建對象并啟動Servlet容器;
先啟動嵌入式的Servlet容器,再將ioc容器中剩下沒有創建出的對象獲取出來;
IOC容器啟動創建嵌入式的Servlet容器
使用外置的Servlet容器
嵌入式Servlet容器:應用打成可執行的jar
​優點:簡單、便攜;
​缺點:默認不支持JSP、優化定制比較復雜(使用定制器【ServerProperties、自定義EmbeddedServletContainerCustomizer】,自己編寫嵌入式Servlet容器的創建工廠【EmbeddedServletContainerFactory】);
外置的Servlet容器:外面安裝Tomcat---應用war包的方式打包;
步驟
1)、必須創建一個war項目;(利用idea創建好目錄結構)
2)、將嵌入式的Tomcat指定為provided;
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency>
3)、必須編寫一個SpringBootServletInitializer的子類,并調用configure方法
public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { //傳入SpringBoot應用的主程序 return application.sources(SpringBoot04WebJspApplication.class); } }
4)、啟動服務器就可以使用;
原理
jar包:執行SpringBoot主類的main方法,啟動ioc容器,創建嵌入式的Servlet容器;
war包:啟動服務器,服務器啟動SpringBoot應用【SpringBootServletInitializer】,啟動ioc容器;
servlet3.0(Spring注解版):
8.2.4 Shared libraries / runtimes pluggability:
規則:
​1)、服務器啟動(web應用啟動)會創建當前web應用里面每一個jar包里面ServletContainerInitializer實例:
​2)、ServletContainerInitializer的實現放在jar包的META-INF/services文件夾下,有一個名為javax.servlet.ServletContainerInitializer的文件,內容就是ServletContainerInitializer的實現類的全類名
​3)、還可以使用@HandlesTypes,在應用啟動的時候加載我們感興趣的類;
流程:
1)、啟動Tomcat
2)、org\springframework\spring-web\4.3.14.RELEASE\spring-web-4.3.14.RELEASE.jar!\META-INF\services\javax.servlet.ServletContainerInitializer:
Spring的web模塊里面有這個文件:org.springframework.web.SpringServletContainerInitializer
3)、SpringServletContainerInitializer將@HandlesTypes(WebApplicationInitializer.class)標注的所有這個類型的類都傳入到onStartup方法的Set<Class<?>>;為這些WebApplicationInitializer類型的類創建實例;
4)、每一個WebApplicationInitializer都調用自己的onStartup;
5)、相當于我們的SpringBootServletInitializer的類會被創建對象,并執行onStartup方法
6)、SpringBootServletInitializer實例執行onStartup的時候會createRootApplicationContext;創建容器
protected WebApplicationContext createRootApplicationContext( ServletContext servletContext) { //1、創建SpringApplicationBuilder SpringApplicationBuilder builder = createSpringApplicationBuilder(); StandardServletEnvironment environment = new StandardServletEnvironment(); environment.initPropertySources(servletContext, null); builder.environment(environment); builder.main(getClass()); ApplicationContext parent = getExistingRootWebApplicationContext(servletContext); if (parent != null) { this.logger.info("Root context already created (using as parent)."); servletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null); builder.initializers(new ParentContextApplicationContextInitializer(parent)); } builder.initializers( new ServletContextApplicationContextInitializer(servletContext)); builder.contextClass(AnnotationConfigEmbeddedWebApplicationContext.class); //調用configure方法,子類重寫了這個方法,將SpringBoot的主程序類傳入了進來 builder = configure(builder); //使用builder創建一個Spring應用 SpringApplication application = builder.build(); if (application.getSources().isEmpty() && AnnotationUtils .findAnnotation(getClass(), Configuration.class) != null) { application.getSources().add(getClass()); } Assert.state(!application.getSources().isEmpty(), "No SpringApplication sources have been defined. Either override the " + "configure method or add an @Configuration annotation"); // Ensure error pages are registered if (this.registerErrorPageFilter) { application.getSources().add(ErrorPageFilterConfiguration.class); } //啟動Spring應用 return run(application); }
7)、Spring的應用就啟動并且創建IOC容器
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; FailureAnalyzers analyzers = null; configureHeadlessProperty(); SpringApplicationRunListeners listeners = getRunListeners(args); listeners.starting(); try { ApplicationArguments applicationArguments = new DefaultApplicationArguments( args); ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments); Banner printedBanner = printBanner(environment); context = createApplicationContext(); analyzers = new FailureAnalyzers(context); prepareContext(context, environment, listeners, applicationArguments, printedBanner); //刷新IOC容器 refreshContext(context); afterRefresh(context, applicationArguments); listeners.finished(context, null); stopWatch.stop(); if (this.logStartupInfo) { new StartupInfoLogger(this.mainApplicationClass) .logStarted(getApplicationLog(), stopWatch); } return context; } catch (Throwable ex) { handleRunFailure(context, listeners, analyzers, ex); throw new IllegalStateException(ex); } }
啟動Servlet容器,再啟動SpringBoot應用
看完了這篇文章,相信你對SpringBoot配置嵌入式Servlet容器和外置Servlet容器的使用方法有了一定的了解,想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。