Home / Class/ ParentContextCloserApplicationListener Class — spring-boot Architecture

ParentContextCloserApplicationListener Class — spring-boot Architecture

Architecture documentation for the ParentContextCloserApplicationListener class in ParentContextCloserApplicationListener.java from the spring-boot codebase.

Entity Profile

Source Code

core/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextCloserApplicationListener.java lines 40–119

public class ParentContextCloserApplicationListener
		implements ApplicationListener<ParentContextAvailableEvent>, ApplicationContextAware, Ordered {

	private static final int ORDER = Ordered.LOWEST_PRECEDENCE - 10;

	@SuppressWarnings("NullAway.Init")
	private ApplicationContext context;

	@Override
	public int getOrder() {
		return ORDER;
	}

	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		this.context = context;
	}

	@Override
	public void onApplicationEvent(ParentContextAvailableEvent event) {
		maybeInstallListenerInParent(event.getApplicationContext());
	}

	private void maybeInstallListenerInParent(ConfigurableApplicationContext child) {
		if (child == this.context && child.getParent() instanceof ConfigurableApplicationContext parent) {
			parent.addApplicationListener(createContextCloserListener(child));
		}
	}

	/**
	 * Subclasses may override to create their own subclass of ContextCloserListener. This
	 * still enforces the use of a weak reference.
	 * @param child the child context
	 * @return the {@link ContextCloserListener} to use
	 */
	protected ContextCloserListener createContextCloserListener(ConfigurableApplicationContext child) {
		return new ContextCloserListener(child);
	}

	/**
	 * {@link ApplicationListener} to close the context.
	 */
	protected static class ContextCloserListener implements ApplicationListener<ContextClosedEvent> {

		private final WeakReference<ConfigurableApplicationContext> childContext;

		public ContextCloserListener(ConfigurableApplicationContext childContext) {
			this.childContext = new WeakReference<>(childContext);
		}

		@Override
		public void onApplicationEvent(ContextClosedEvent event) {
			ConfigurableApplicationContext context = this.childContext.get();
			if ((context != null) && (event.getApplicationContext() == context.getParent()) && context.isActive()) {
				context.close();
			}
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj) {
				return true;
			}
			if (obj == null) {
				return false;
			}
			if (obj instanceof ContextCloserListener other) {
				return ObjectUtils.nullSafeEquals(this.childContext.get(), other.childContext.get());
			}
			return super.equals(obj);
		}

		@Override
		public int hashCode() {
			return ObjectUtils.nullSafeHashCode(this.childContext.get());
		}

	}

}

Analyze Your Own Codebase

Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.

Try Supermodel Free