程序中定制自己的启动容器

doMore 644 2019-11-04

除了在 application.properties 中配置关于servlet容器的信息之外,还可以通过编程的方式配置。 例如:

import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;

@Component
public class CustomizationBean implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

	@Override
	public void customize(ConfigurableServletWebServerFactory server) {
		server.setPort(9000);
	}

}

能够配置的不仅仅有ConfigurableServletWebServerFactory,还有ConfigurableTomcatWebServerFactory ,ConfigurableJettyWebServerFactory 等springboot内嵌的容器。 如果在原有的配置上修改不够痛快,有限制。可以直接注入ConfigurableServletWebServerFactory。如下:

@Bean
public ConfigurableServletWebServerFactory webServerFactory() {
        // JettyServletWebServerFactory, or UndertowServletWebServerFactory
	TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
	factory.setPort(9000);
	factory.setSessionTimeout(10, TimeUnit.MINUTES);
	factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html"));
	return factory;
}