org.springframework.beans.factory.DisposableBean Java Examples

The following examples show how to use org.springframework.beans.factory.DisposableBean. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ContextCleanupListener.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Find all ServletContext attributes which implement {@link DisposableBean}
 * and destroy them, removing all affected ServletContext attributes eventually.
 * @param sc the ServletContext to check
 */
static void cleanupAttributes(ServletContext sc) {
	Enumeration<String> attrNames = sc.getAttributeNames();
	while (attrNames.hasMoreElements()) {
		String attrName = attrNames.nextElement();
		if (attrName.startsWith("org.springframework.")) {
			Object attrValue = sc.getAttribute(attrName);
			if (attrValue instanceof DisposableBean) {
				try {
					((DisposableBean) attrValue).destroy();
				}
				catch (Throwable ex) {
					logger.error("Couldn't invoke destroy method of attribute with name '" + attrName + "'", ex);
				}
			}
		}
	}
}
 
Example #2
Source File: ContextCleanupListener.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Find all ServletContext attributes which implement {@link DisposableBean}
 * and destroy them, removing all affected ServletContext attributes eventually.
 * @param sc the ServletContext to check
 */
static void cleanupAttributes(ServletContext sc) {
	Enumeration<String> attrNames = sc.getAttributeNames();
	while (attrNames.hasMoreElements()) {
		String attrName = attrNames.nextElement();
		if (attrName.startsWith("org.springframework.")) {
			Object attrValue = sc.getAttribute(attrName);
			if (attrValue instanceof DisposableBean) {
				try {
					((DisposableBean) attrValue).destroy();
				}
				catch (Throwable ex) {
					logger.error("Couldn't invoke destroy method of attribute with name '" + attrName + "'", ex);
				}
			}
		}
	}
}
 
Example #3
Source File: DisposableBeanAdapter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * If the current value of the given beanDefinition's "destroyMethodName" property is
 * {@link AbstractBeanDefinition#INFER_METHOD}, then attempt to infer a destroy method.
 * Candidate methods are currently limited to public, no-arg methods named "close" or
 * "shutdown" (whether declared locally or inherited). The given BeanDefinition's
 * "destroyMethodName" is updated to be null if no such method is found, otherwise set
 * to the name of the inferred method. This constant serves as the default for the
 * {@code @Bean#destroyMethod} attribute and the value of the constant may also be
 * used in XML within the {@code <bean destroy-method="">} or {@code
 * <beans default-destroy-method="">} attributes.
 * <p>Also processes the {@link java.io.Closeable} and {@link java.lang.AutoCloseable}
 * interfaces, reflectively calling the "close" method on implementing beans as well.
 */
private String inferDestroyMethodIfNecessary(Object bean, RootBeanDefinition beanDefinition) {
	String destroyMethodName = beanDefinition.getDestroyMethodName();
	if (AbstractBeanDefinition.INFER_METHOD.equals(destroyMethodName) ||
			(destroyMethodName == null && closeableInterface.isInstance(bean))) {
		// Only perform destroy method inference or Closeable detection
		// in case of the bean not explicitly implementing DisposableBean
		if (!(bean instanceof DisposableBean)) {
			try {
				return bean.getClass().getMethod(CLOSE_METHOD_NAME).getName();
			}
			catch (NoSuchMethodException ex) {
				try {
					return bean.getClass().getMethod(SHUTDOWN_METHOD_NAME).getName();
				}
				catch (NoSuchMethodException ex2) {
					// no candidate destroy method found
				}
			}
		}
		return null;
	}
	return (StringUtils.hasLength(destroyMethodName) ? destroyMethodName : null);
}
 
Example #4
Source File: AbstractPrototypeBasedTargetSource.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Subclasses should call this method to destroy an obsolete prototype instance.
 * @param target the bean instance to destroy
 */
protected void destroyPrototypeInstance(Object target) {
	if (logger.isDebugEnabled()) {
		logger.debug("Destroying instance of bean '" + getTargetBeanName() + "'");
	}
	if (getBeanFactory() instanceof ConfigurableBeanFactory) {
		((ConfigurableBeanFactory) getBeanFactory()).destroyBean(getTargetBeanName(), target);
	}
	else if (target instanceof DisposableBean) {
		try {
			((DisposableBean) target).destroy();
		}
		catch (Throwable ex) {
			logger.warn("Destroy method on bean with name '" + getTargetBeanName() + "' threw an exception", ex);
		}
	}
}
 
Example #5
Source File: AbstractPrototypeBasedTargetSource.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Subclasses should call this method to destroy an obsolete prototype instance.
 * @param target the bean instance to destroy
 */
protected void destroyPrototypeInstance(Object target) {
	if (this.logger.isDebugEnabled()) {
		this.logger.debug("Destroying instance of bean '" + getTargetBeanName() + "'");
	}
	if (getBeanFactory() instanceof ConfigurableBeanFactory) {
		((ConfigurableBeanFactory) getBeanFactory()).destroyBean(getTargetBeanName(), target);
	}
	else if (target instanceof DisposableBean) {
		try {
			((DisposableBean) target).destroy();
		}
		catch (Throwable ex) {
			logger.error("Couldn't invoke destroy method of bean with name '" + getTargetBeanName() + "'", ex);
		}
	}
}
 
Example #6
Source File: ClientHttpRequestFactoryFactoryIntegrationTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void httpComponentsClientUsingPemShouldWork() throws Exception {

	File caCertificate = new File(Settings.findWorkDir(), "ca/certs/ca.cert.pem");
	SslConfiguration sslConfiguration = SslConfiguration.forTrustStore(SslConfiguration.KeyStoreConfiguration
			.of(new FileSystemResource(caCertificate)).withStoreType(SslConfiguration.PEM_KEYSTORE_TYPE));

	ClientHttpRequestFactory factory = HttpComponents.usingHttpComponents(new ClientOptions(), sslConfiguration);
	RestTemplate template = new RestTemplate(factory);

	String response = request(template);

	assertThat(factory).isInstanceOf(HttpComponentsClientHttpRequestFactory.class);
	assertThat(response).isNotNull().contains("initialized");

	((DisposableBean) factory).destroy();
}
 
Example #7
Source File: AbstractAnnotationBeanPostProcessor.java    From spring-context-support with Apache License 2.0 6 votes vote down vote up
@Override
public void destroy() throws Exception {

    for (Object object : injectedObjectsCache.values()) {
        if (logger.isInfoEnabled()) {
            logger.info(object + " was destroying!");
        }

        if (object instanceof DisposableBean) {
            ((DisposableBean) object).destroy();
        }
    }

    injectionMetadataCache.clear();
    injectedObjectsCache.clear();

    if (logger.isInfoEnabled()) {
        logger.info(getClass() + " was destroying!");
    }

}
 
Example #8
Source File: AnnotationInjectedBeanPostProcessor.java    From spring-context-support with Apache License 2.0 6 votes vote down vote up
@Override
public void destroy() throws Exception {

    for (Object object : injectedObjectsCache.values()) {
        if (logger.isInfoEnabled()) {
            logger.info(object + " was destroying!");
        }

        if (object instanceof DisposableBean) {
            ((DisposableBean) object).destroy();
        }
    }

    injectionMetadataCache.clear();
    injectedObjectsCache.clear();

    if (logger.isInfoEnabled()) {
        logger.info(getClass() + " was destroying!");
    }

}
 
Example #9
Source File: DisposableBeanAdapter.java    From blog_demos with Apache License 2.0 6 votes vote down vote up
/**
 * If the current value of the given beanDefinition's "destroyMethodName" property is
 * {@link AbstractBeanDefinition#INFER_METHOD}, then attempt to infer a destroy method.
 * Candidate methods are currently limited to public, no-arg methods named "close"
 * (whether declared locally or inherited). The given BeanDefinition's
 * "destroyMethodName" is updated to be null if no such method is found, otherwise set
 * to the name of the inferred method. This constant serves as the default for the
 * {@code @Bean#destroyMethod} attribute and the value of the constant may also be
 * used in XML within the {@code <bean destroy-method="">} or {@code
 * <beans default-destroy-method="">} attributes.
 * <p>Also processes the {@link Closeable} and {@link AutoCloseable}
 * interfaces, reflectively calling the "close" method on implementing beans as well.
 */
private String inferDestroyMethodIfNecessary(Object bean, RootBeanDefinition beanDefinition) {
	if (AbstractBeanDefinition.INFER_METHOD.equals(beanDefinition.getDestroyMethodName()) ||
			(beanDefinition.getDestroyMethodName() == null && closeableInterface.isInstance(bean))) {
		// Only perform destroy method inference or Closeable detection
		// in case of the bean not explicitly implementing DisposableBean
		if (!(bean instanceof DisposableBean)) {
			try {
				return bean.getClass().getMethod(CLOSE_METHOD_NAME).getName();
			}
			catch (NoSuchMethodException ex) {
				try {
					return bean.getClass().getMethod(SHUTDOWN_METHOD_NAME).getName();
				}
				catch (NoSuchMethodException ex2) {
					// no candidate destroy method found
				}
			}
		}
		return null;
	}
	return beanDefinition.getDestroyMethodName();
}
 
Example #10
Source File: DisposableBeanAdapter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * If the current value of the given beanDefinition's "destroyMethodName" property is
 * {@link AbstractBeanDefinition#INFER_METHOD}, then attempt to infer a destroy method.
 * Candidate methods are currently limited to public, no-arg methods named "close" or
 * "shutdown" (whether declared locally or inherited). The given BeanDefinition's
 * "destroyMethodName" is updated to be null if no such method is found, otherwise set
 * to the name of the inferred method. This constant serves as the default for the
 * {@code @Bean#destroyMethod} attribute and the value of the constant may also be
 * used in XML within the {@code <bean destroy-method="">} or {@code
 * <beans default-destroy-method="">} attributes.
 * <p>Also processes the {@link java.io.Closeable} and {@link java.lang.AutoCloseable}
 * interfaces, reflectively calling the "close" method on implementing beans as well.
 */
@Nullable
private String inferDestroyMethodIfNecessary(Object bean, RootBeanDefinition beanDefinition) {
	String destroyMethodName = beanDefinition.getDestroyMethodName();
	if (AbstractBeanDefinition.INFER_METHOD.equals(destroyMethodName) ||
			(destroyMethodName == null && bean instanceof AutoCloseable)) {
		// Only perform destroy method inference or Closeable detection
		// in case of the bean not explicitly implementing DisposableBean
		if (!(bean instanceof DisposableBean)) {
			try {
				return bean.getClass().getMethod(CLOSE_METHOD_NAME).getName();
			}
			catch (NoSuchMethodException ex) {
				try {
					return bean.getClass().getMethod(SHUTDOWN_METHOD_NAME).getName();
				}
				catch (NoSuchMethodException ex2) {
					// no candidate destroy method found
				}
			}
		}
		return null;
	}
	return (StringUtils.hasLength(destroyMethodName) ? destroyMethodName : null);
}
 
Example #11
Source File: SakaiContextLoaderListener.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Find all ServletContext attributes which implement {@link DisposableBean}
 * and destroy them, removing all affected ServletContext attributes eventually.
 * @param sc the ServletContext to check
 */
private static void cleanupAttributes(ServletContext sc) {
	Enumeration<String> attrNames = sc.getAttributeNames();
	while (attrNames.hasMoreElements()) {
		String attrName = attrNames.nextElement();
		if (attrName.startsWith("org.springframework.")) {
			Object attrValue = sc.getAttribute(attrName);
			if (attrValue instanceof DisposableBean) {
				try {
					((DisposableBean) attrValue).destroy();
				}
				catch (Throwable ex) {
					log.error("Couldn't invoke destroy method of attribute with name '" + attrName + "'", ex);
				}
			}
		}
	}
}
 
Example #12
Source File: DisposableBeanAdapter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * If the current value of the given beanDefinition's "destroyMethodName" property is
 * {@link AbstractBeanDefinition#INFER_METHOD}, then attempt to infer a destroy method.
 * Candidate methods are currently limited to public, no-arg methods named "close" or
 * "shutdown" (whether declared locally or inherited). The given BeanDefinition's
 * "destroyMethodName" is updated to be null if no such method is found, otherwise set
 * to the name of the inferred method. This constant serves as the default for the
 * {@code @Bean#destroyMethod} attribute and the value of the constant may also be
 * used in XML within the {@code <bean destroy-method="">} or {@code
 * <beans default-destroy-method="">} attributes.
 * <p>Also processes the {@link java.io.Closeable} and {@link java.lang.AutoCloseable}
 * interfaces, reflectively calling the "close" method on implementing beans as well.
 */
private String inferDestroyMethodIfNecessary(Object bean, RootBeanDefinition beanDefinition) {
	String destroyMethodName = beanDefinition.getDestroyMethodName();
	if (AbstractBeanDefinition.INFER_METHOD.equals(destroyMethodName) ||
			(destroyMethodName == null && closeableInterface.isInstance(bean))) {
		// Only perform destroy method inference or Closeable detection
		// in case of the bean not explicitly implementing DisposableBean
		if (!(bean instanceof DisposableBean)) {
			try {
				return bean.getClass().getMethod(CLOSE_METHOD_NAME).getName();
			}
			catch (NoSuchMethodException ex) {
				try {
					return bean.getClass().getMethod(SHUTDOWN_METHOD_NAME).getName();
				}
				catch (NoSuchMethodException ex2) {
					// no candidate destroy method found
				}
			}
		}
		return null;
	}
	return (StringUtils.hasLength(destroyMethodName) ? destroyMethodName : null);
}
 
Example #13
Source File: ContextCleanupListener.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Find all ServletContext attributes which implement {@link DisposableBean}
 * and destroy them, removing all affected ServletContext attributes eventually.
 * @param sc the ServletContext to check
 */
static void cleanupAttributes(ServletContext sc) {
	Enumeration<String> attrNames = sc.getAttributeNames();
	while (attrNames.hasMoreElements()) {
		String attrName = attrNames.nextElement();
		if (attrName.startsWith("org.springframework.")) {
			Object attrValue = sc.getAttribute(attrName);
			if (attrValue instanceof DisposableBean) {
				try {
					((DisposableBean) attrValue).destroy();
				}
				catch (Throwable ex) {
					logger.error("Couldn't invoke destroy method of attribute with name '" + attrName + "'", ex);
				}
			}
		}
	}
}
 
Example #14
Source File: ExceptionHandlingAsyncTaskExecutor.java    From jhipster with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void destroy() throws Exception {
    if (executor instanceof DisposableBean) {
        DisposableBean bean = (DisposableBean) executor;
        bean.destroy();
    }
}
 
Example #15
Source File: _ExceptionHandlingAsyncTaskExecutor.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void destroy() throws Exception {
    if (executor instanceof DisposableBean) {
        DisposableBean bean = (DisposableBean) executor;
        bean.destroy();
    }
}
 
Example #16
Source File: ExceptionHandlingAsyncTaskExecutor.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void destroy() throws Exception {
    if (executor instanceof DisposableBean) {
        DisposableBean bean = (DisposableBean) executor;
        bean.destroy();
    }
}
 
Example #17
Source File: ExceptionHandlingAsyncTaskExecutor.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void destroy() throws Exception {
    if (executor instanceof DisposableBean) {
        DisposableBean bean = (DisposableBean) executor;
        bean.destroy();
    }
}
 
Example #18
Source File: TestRestTemplateFactory.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private static void initializeClientHttpRequestFactory(SslConfiguration sslConfiguration) throws Exception {

		if (factoryCache.get() != null) {
			return;
		}

		final ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory
				.create(new ClientOptions(), sslConfiguration);

		if (factoryCache.compareAndSet(null, clientHttpRequestFactory)) {

			if (clientHttpRequestFactory instanceof InitializingBean) {
				((InitializingBean) clientHttpRequestFactory).afterPropertiesSet();
			}

			if (clientHttpRequestFactory instanceof DisposableBean) {

				Runtime.getRuntime().addShutdownHook(new Thread("ClientHttpRequestFactory Shutdown Hook") {

					@Override
					public void run() {
						try {
							((DisposableBean) clientHttpRequestFactory).destroy();
						}
						catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			}
		}
	}
 
Example #19
Source File: ClientHttpRequestFactoryFactoryIntegrationTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void nettyClientShouldWork() throws Exception {

	ClientHttpRequestFactory factory = Netty.usingNetty(new ClientOptions(), Settings.createSslConfiguration());
	((InitializingBean) factory).afterPropertiesSet();
	RestTemplate template = new RestTemplate(factory);

	String response = request(template);

	assertThat(factory).isInstanceOf(Netty4ClientHttpRequestFactory.class);
	assertThat(response).isNotNull().contains("initialized");

	((DisposableBean) factory).destroy();
}
 
Example #20
Source File: ExceptionHandlingAsyncTaskExecutor.java    From ServiceCutter with Apache License 2.0 5 votes vote down vote up
@Override
public void destroy() throws Exception {
    if (executor instanceof DisposableBean) {
        DisposableBean bean = (DisposableBean) executor;
        bean.destroy();
    }
}
 
Example #21
Source File: SecretLeaseContainer.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
/**
 * Shutdown this {@link SecretLeaseContainer}, disable lease renewal and revoke
 * leases.
 *
 * @see #afterPropertiesSet()
 * @see #start()
 * @see #stop()
 */
@Override
public void destroy() throws Exception {

	int status = this.status;

	if (status == STATUS_INITIAL || status == STATUS_STARTED) {

		if (UPDATER.compareAndSet(this, status, STATUS_DESTROYED)) {

			for (Entry<RequestedSecret, LeaseRenewalScheduler> entry : this.renewals.entrySet()) {

				Lease lease = entry.getValue().getLease();
				entry.getValue().disableScheduleRenewal();

				if (lease != null && lease.hasLeaseId()) {
					doRevokeLease(entry.getKey(), lease);
				}
			}

			if (this.manageTaskScheduler) {

				if (this.taskScheduler instanceof DisposableBean) {
					((DisposableBean) this.taskScheduler).destroy();
					this.taskScheduler = null;
				}
			}
		}
	}
}
 
Example #22
Source File: DataReceiverGroupTest.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private void closeBean(DisposableBean bean) {
    try {
        if (bean != null) {
            bean.destroy();
        }
    } catch (Exception e) {
        // ignore
    }
}
 
Example #23
Source File: ExceptionHandlingAsyncTaskExecutor.java    From gpmr with Apache License 2.0 5 votes vote down vote up
@Override
public void destroy() throws Exception {
    if (executor instanceof DisposableBean) {
        DisposableBean bean = (DisposableBean) executor;
        bean.destroy();
    }
}
 
Example #24
Source File: DisposableBeanAdapter.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new DisposableBeanAdapter for the given bean.
 * @param bean the bean instance (never {@code null})
 * @param postProcessors the List of BeanPostProcessors
 * (potentially DestructionAwareBeanPostProcessor), if any
 */
public DisposableBeanAdapter(Object bean, List<BeanPostProcessor> postProcessors, AccessControlContext acc) {
	Assert.notNull(bean, "Disposable bean must not be null");
	this.bean = bean;
	this.beanName = null;
	this.invokeDisposableBean = (this.bean instanceof DisposableBean);
	this.nonPublicAccessAllowed = true;
	this.acc = acc;
	this.beanPostProcessors = filterPostProcessors(postProcessors);
}
 
Example #25
Source File: DisposableBeanAdapter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a new DisposableBeanAdapter for the given bean.
 * @param bean the bean instance (never {@code null})
 * @param postProcessors the List of BeanPostProcessors
 * (potentially DestructionAwareBeanPostProcessor), if any
 */
public DisposableBeanAdapter(Object bean, List<BeanPostProcessor> postProcessors, AccessControlContext acc) {
	Assert.notNull(bean, "Disposable bean must not be null");
	this.bean = bean;
	this.beanName = null;
	this.invokeDisposableBean = (this.bean instanceof DisposableBean);
	this.nonPublicAccessAllowed = true;
	this.acc = acc;
	this.beanPostProcessors = filterPostProcessors(postProcessors, bean);
}
 
Example #26
Source File: ExceptionHandlingAsyncTaskExecutor.java    From klask-io with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void destroy() throws Exception {
    if (executor instanceof DisposableBean) {
        DisposableBean bean = (DisposableBean) executor;
        bean.destroy();
    }
}
 
Example #27
Source File: ClientHttpRequestFactoryFactoryTests.java    From spring-credhub with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void nettyClientCreated() throws Exception {
	ClientHttpRequestFactory factory = Netty.usingNetty(new ClientOptions());

	assertThat(factory).isInstanceOf(Netty4ClientHttpRequestFactory.class);

	((DisposableBean) factory).destroy();
}
 
Example #28
Source File: ClientHttpRequestFactoryFactoryTests.java    From spring-credhub with Apache License 2.0 5 votes vote down vote up
@Test
public void okHttp3ClientCreated() throws Exception {
	ClientHttpRequestFactory factory = OkHttp3.usingOkHttp3(new ClientOptions());

	assertThat(factory).isInstanceOf(OkHttp3ClientHttpRequestFactory.class);

	((DisposableBean) factory).destroy();
}
 
Example #29
Source File: RabbitMessageChannelBinder.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 5 votes vote down vote up
@Override
public void destroy() throws Exception {
	if (this.connectionFactory instanceof DisposableBean) {
		if (this.destroyConnectionFactory) {
			((DisposableBean) this.connectionFactory).destroy();
		}
	}
}
 
Example #30
Source File: DisposableBeanAdapter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check whether the given bean has any kind of destroy method to call.
 * @param bean the bean instance
 * @param beanDefinition the corresponding bean definition
 */
public static boolean hasDestroyMethod(Object bean, RootBeanDefinition beanDefinition) {
	if (bean instanceof DisposableBean || closeableInterface.isInstance(bean)) {
		return true;
	}
	String destroyMethodName = beanDefinition.getDestroyMethodName();
	if (AbstractBeanDefinition.INFER_METHOD.equals(destroyMethodName)) {
		return (ClassUtils.hasMethod(bean.getClass(), CLOSE_METHOD_NAME) ||
				ClassUtils.hasMethod(bean.getClass(), SHUTDOWN_METHOD_NAME));
	}
	return StringUtils.hasLength(destroyMethodName);
}