Spring Boot server.port配置原理

本文深入探讨了SpringBoot中server.port配置项的生效过程,从autoConfigure机制到WebServerFactoryCustomizerBeanPostProcessor的beanPostProcess原理,再到嵌入式Tomcat的配置流程,解析了Port设置的复杂过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

       我们经常配置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。

<think>嗯,用户现在想了解Spring中的spring.application.json配置的具体作用和内容。我之前已经回答过关于PropertySource的问题,现在需要结合新的引用信息来解答这个。首先,我需要回顾用户提供的引用内容。引用[1]提到,SpringBoot允许将属性块编码为单个JSON结构,通过spring.application.json或SPRING_APPLICATION_JSON环境变量来解析并添加到环境中。这说明这个配置是用来处理复杂属性结构的,可能解决环境变量命名限制的问题。用户的问题集中在spring.application.json的作用和内容。我需要解释它的用途,比如如何传递JSON格式的配置,以及它在Spring环境中的加载方式。可能需要举例说明JSON结构,以及如何通过命令行或环境变量设置。另外,引用[3]和[4]涉及JSON转换器和配置,可能与属性解析后的处理有关,但用户的问题主要集中在配置本身,所以这部分可能不需要深入,除非需要说明转换器如何处理JSON数据,但可能不相关。接下来,我需要确定如何组织回答。结构应该包括定义、作用、配置方式、示例和注意事项。同时,引用[1]需要被正确标注,确保每个引用点都自然插入到相关内容后面。还要考虑用户可能的困惑点,比如如何正确设置这个JSON配置,或者它和环境变量、系统属性的优先级关系。此外,需要强调为什么使用这种方式,比如解决命名限制或复杂结构的问题。最后,生成的相关问题需要与主题相关,比如如何设置、优先级问题、与@Value注解的配合使用,以及可能出现的异常处理,这可以参考引用中的其他信息,比如转换异常的情况。</think>### Spring中`spring.application.json`配置详解 #### 一、核心定义与作用 `spring.application.json`是Spring Boot提供的一种**结构化属性注入机制**,允许通过JSON格式一次性传递多个层级化配置。其核心作用包括: 1. **突破环境变量命名限制** 环境变量和系统属性通常不支持`.`或复杂结构(如`app.server.url`),通过JSON编码可将嵌套属性一次性传递[^1]。 2. **动态配置注入** 在容器化部署场景中,可通过命令行参数或环境变量直接注入配置,无需修改配置文件。 #### 二、配置方式与语法 ##### 1. 命令行启动参数 ```bash java -jar app.jar --spring.application.json='{"app":{"name":"demo","threads":5}}' ``` ##### 2. 环境变量设置 ```bash # Linux/MacOS export SPRING_APPLICATION_JSON='{"logging.level.root":"DEBUG"}' # Windows set SPRING_APPLICATION_JSON={"datasource.url":"jdbc:h2:mem:test"} ``` ##### 3. JSON结构示例 ```json { "server": { "port": 8081, "ssl": { "enabled": true, "key-store": "classpath:keystore.jks" } }, "spring.profiles.active": "prod" } ``` #### 三、技术实现原理 1. **优先级规则** `spring.application.json`的优先级低于`application.properties`但高于系统环境变量,其加载顺序遵循Spring Boot的标准属性源顺序[^1]。 2. **解析流程** Spring Boot在启动时通过`SpringApplicationJsonEnvironmentPostProcessor`解析JSON内容,将其转换为扁平化属性键值对,例如: ```properties server.port=8081 server.ssl.enabled=true ``` 3. **与Jackson的关联** 底层使用Jackson库进行JSON解析(如引用[4]中的`MappingJackson2HttpMessageConverter`),因此支持所有Jackson支持的JSON特性[^4]。 #### 四、典型应用场景 1. **容器化配置** 在Kubernetes中通过Pod环境变量注入配置: ```yaml env: - name: SPRING_APPLICATION_JSON value: '{"cache.max-size": 1000}' ``` 2. **临时调试配置** 开发时快速覆盖特定配置: ```bash SPRING_APPLICATION_JSON='{"spring.h2.console.enabled":true}' mvn spring-boot:run ``` 3. **多层级配置合并** 将多个配置块合并传递: ```json { "spring": { "datasource.url": "jdbc:mysql://localhost/test", "jpa.show-sql": true } } ``` #### 五、注意事项 - **转义字符处理** 在命令行中使用时需注意引号转义,例如Windows需使用双引号包裹: ```cmd set SPRING_APPLICATION_JSON={"key":"value"} ``` - **数据类型校验** JSON中的数值类型(如`"threads":5`)会被解析为Integer,需确保与目标字段类型匹配 - **与@Value注解协同** 可通过`@Value("${app.name}")`直接注入JSON中的属性值[^1]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值