本节将对ServerPortInfoApplicationContextInitializer进行分析,关于该对象的基础定义代码如下:
public class ServerPortInfoApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>, ApplicationListener <WebServerInitializedEvent>{}
从基础定义上可以发现该对象是ApplicationListener的实现类,下面关注Application-ContextInitializer的实现代码,具体方法如下:
public void initialize(ConfigurableApplicationContext applicationContext) { applicationContext.addApplicationListener(this); }
在这段代码中会给应用上下文添加应用监听器,这里添加的对象是自身。关于应用监听器相关的实现代码如下:
public void onApplicationEvent(WebServerInitializedEvent event) { String propertyName = "local." + getName(event.getApplicationContext()) + ".port"; setPortProperty(event.getApplicationContext(), propertyName, event.getWebServer().getPort()); }
在上述代码中主要的处理流程如下:
(1)获取属性名称;
(2)设置属性。
上述流程中关于属性设置主要是和环境接口进行交互处理,具体处理代码如下:
@SuppressWarnings("unchecked") private void setPortProperty(ConfigurableEnvironment environment, String propertyName, int port) { MutablePropertySources sources = environment.getPropertySources(); PropertySource<?> source = sources.get("server.ports"); if (source == null) { source = new MapPropertySource("server.ports", new HashMap<>()); sources.addFirst(source); } ((Map<String, Object>) source.getSource()).put(propertyName, port); }