解決springboot application.properties server.port配置問題

springboot application.properties server.port配置的問題

近年來,springboot以其快速構建方便便捷,開箱即用,約定優於配置(Convention Over Configuration)的特性深受廣大開發者喜愛。

springboot已經集成配置好瞭一套web開發的默認配置,開發者可以無需修改任何配置即可開始一個web工程,但是實際情況中有時候開發者還是需要修改部分默認配置項來使其更加契合自己的項目需求。

下面就其中一個小問題做個記錄

在配置服務啟動的端口時,springboot默認在application.properties配置文件中提供瞭server.port配置項來

讓開發者自行配置服務啟動端口號,**但是註意:**

#服務啟動端口號
server.port=8889

該配置項要想生效其實是依賴於項目中內嵌的tomcat容器,如下圖:

內嵌tomcat的jar包依賴包含在pom中

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

如果pom中不引人上述依賴,那麼項目中不會導入內嵌tomcat的jar包,相應的application.properties配置文件中server.port配置項也將無法生效,因為該配置項實際上修改的就是內嵌tomcat的web端口號。

Spring Boot server.port配置原理

我們經常配置server.port=xxx,但其實這是一個比較復雜的過程才生效的,這次講講生效的過程。

1. autoConfigure

本質來源於自動配置

org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration

TomcatServletWebServerFactory

為什麼是這個類,核心是beanPostProcess原理

@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
public class ServerProperties {
 
	/**
	 * Server HTTP port.
	 */
	private Integer port;

beanPostProcess

public class WebServerFactoryCustomizerBeanPostProcessor implements BeanPostProcessor, BeanFactoryAware {
 
	private ListableBeanFactory beanFactory; 
	private List<WebServerFactoryCustomizer<?>> customizers;  
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		if (bean instanceof WebServerFactory) {
			postProcessBeforeInitialization((WebServerFactory) bean);
		}
		return bean;
	} 
	
	@SuppressWarnings("unchecked")
	private void postProcessBeforeInitialization(WebServerFactory webServerFactory) {
		LambdaSafe.callbacks(WebServerFactoryCustomizer.class, getCustomizers(), webServerFactory)
				.withLogger(WebServerFactoryCustomizerBeanPostProcessor.class)
				.invoke((customizer) -> customizer.customize(webServerFactory));
	}
 
    private Collection<WebServerFactoryCustomizer<?>> getCustomizers() {
		if (this.customizers == null) {
			// Look up does not include the parent context
			this.customizers = new ArrayList<>(getWebServerFactoryCustomizerBeans());
			this.customizers.sort(AnnotationAwareOrderComparator.INSTANCE);
			this.customizers = Collections.unmodifiableList(this.customizers);
		}
		return this.customizers;
	}
 
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private Collection<WebServerFactoryCustomizer<?>> getWebServerFactoryCustomizerBeans() {
		return (Collection) this.beanFactory.getBeansOfType(WebServerFactoryCustomizer.class, false, false).values();
	}

最終

beanFactory.getBeansOfType(WebServerFactoryCustomizer.class, false, false).values()

WebServerFactoryCustomizer對象.customize(webServerFactory)

@Configuration
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnClass(ServletRequest.class)
@ConditionalOnWebApplication(type = Type.SERVLET)
@EnableConfigurationProperties(ServerProperties.class)
@Import({ ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class,
		ServletWebServerFactoryConfiguration.EmbeddedTomcat.class,
		ServletWebServerFactoryConfiguration.EmbeddedJetty.class,
		ServletWebServerFactoryConfiguration.EmbeddedUndertow.class })
public class ServletWebServerFactoryAutoConfiguration {
 
	@Bean
	public ServletWebServerFactoryCustomizer servletWebServerFactoryCustomizer(ServerProperties serverProperties) {
		return new ServletWebServerFactoryCustomizer(serverProperties);
	}

這裡就將port設置好瞭。

這裡使用函數式編程,lambda表達式,將port的值設置進瞭

ConfigurableServletWebServerFactory ,即TomcatServletWebServerFactory對象

2. embed tomcat如何使用

tomcat創建時,會通過getBean方式獲取工廠

就是 TomcatServletWebServerFactory

然後設置connector,從TomcatServletWebServerFactory讀取port,設置connector,設置結束

總結

Spring Boot在解耦的時候繞瞭很多彎,先@Bean factory對象,然後BeanPostProcess,然後啟動embed tomcat 在factory 中new Tomcat 然後設置Connector,設置port。

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: