Search in sources :

Example 21 with Lifecycle

use of org.springframework.context.Lifecycle in project spring-framework by spring-projects.

the class DefaultLifecycleProcessor method getLifecycleBeans.

// overridable hooks
/**
 * Retrieve all applicable Lifecycle beans: all singletons that have already been created,
 * as well as all SmartLifecycle beans (even if they are marked as lazy-init).
 * @return the Map of applicable beans, with bean names as keys and bean instances as values
 */
protected Map<String, Lifecycle> getLifecycleBeans() {
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    Map<String, Lifecycle> beans = new LinkedHashMap<>();
    String[] beanNames = beanFactory.getBeanNamesForType(Lifecycle.class, false, false);
    for (String beanName : beanNames) {
        String beanNameToRegister = BeanFactoryUtils.transformedBeanName(beanName);
        boolean isFactoryBean = beanFactory.isFactoryBean(beanNameToRegister);
        String beanNameToCheck = (isFactoryBean ? BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName);
        if ((beanFactory.containsSingleton(beanNameToRegister) && (!isFactoryBean || matchesBeanType(Lifecycle.class, beanNameToCheck, beanFactory))) || matchesBeanType(SmartLifecycle.class, beanNameToCheck, beanFactory)) {
            Object bean = beanFactory.getBean(beanNameToCheck);
            if (bean != this && bean instanceof Lifecycle) {
                beans.put(beanNameToRegister, (Lifecycle) bean);
            }
        }
    }
    return beans;
}
Also used : Lifecycle(org.springframework.context.Lifecycle) SmartLifecycle(org.springframework.context.SmartLifecycle) SmartLifecycle(org.springframework.context.SmartLifecycle) ConfigurableListableBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) LinkedHashMap(java.util.LinkedHashMap)

Example 22 with Lifecycle

use of org.springframework.context.Lifecycle in project spring-framework by spring-projects.

the class DefaultLifecycleProcessorTests method mixedShutdown.

@Test
public void mixedShutdown() throws Exception {
    CopyOnWriteArrayList<Lifecycle> stoppedBeans = new CopyOnWriteArrayList<>();
    Lifecycle bean1 = TestLifecycleBean.forShutdownTests(stoppedBeans);
    Lifecycle bean2 = TestSmartLifecycleBean.forShutdownTests(500, 200, stoppedBeans);
    Lifecycle bean3 = TestSmartLifecycleBean.forShutdownTests(Integer.MAX_VALUE, 100, stoppedBeans);
    Lifecycle bean4 = TestLifecycleBean.forShutdownTests(stoppedBeans);
    Lifecycle bean5 = TestSmartLifecycleBean.forShutdownTests(1, 200, stoppedBeans);
    Lifecycle bean6 = TestSmartLifecycleBean.forShutdownTests(-1, 100, stoppedBeans);
    Lifecycle bean7 = TestSmartLifecycleBean.forShutdownTests(Integer.MIN_VALUE, 300, stoppedBeans);
    StaticApplicationContext context = new StaticApplicationContext();
    context.getBeanFactory().registerSingleton("bean1", bean1);
    context.getBeanFactory().registerSingleton("bean2", bean2);
    context.getBeanFactory().registerSingleton("bean3", bean3);
    context.getBeanFactory().registerSingleton("bean4", bean4);
    context.getBeanFactory().registerSingleton("bean5", bean5);
    context.getBeanFactory().registerSingleton("bean6", bean6);
    context.getBeanFactory().registerSingleton("bean7", bean7);
    context.refresh();
    assertThat(bean2.isRunning()).isTrue();
    assertThat(bean3.isRunning()).isTrue();
    assertThat(bean5.isRunning()).isTrue();
    assertThat(bean6.isRunning()).isTrue();
    assertThat(bean7.isRunning()).isTrue();
    assertThat(bean1.isRunning()).isFalse();
    assertThat(bean4.isRunning()).isFalse();
    bean1.start();
    bean4.start();
    assertThat(bean1.isRunning()).isTrue();
    assertThat(bean4.isRunning()).isTrue();
    context.stop();
    assertThat(bean1.isRunning()).isFalse();
    assertThat(bean2.isRunning()).isFalse();
    assertThat(bean3.isRunning()).isFalse();
    assertThat(bean4.isRunning()).isFalse();
    assertThat(bean5.isRunning()).isFalse();
    assertThat(bean6.isRunning()).isFalse();
    assertThat(bean7.isRunning()).isFalse();
    assertThat(stoppedBeans.size()).isEqualTo(7);
    assertThat(getPhase(stoppedBeans.get(0))).isEqualTo(Integer.MAX_VALUE);
    assertThat(getPhase(stoppedBeans.get(1))).isEqualTo(500);
    assertThat(getPhase(stoppedBeans.get(2))).isEqualTo(1);
    assertThat(getPhase(stoppedBeans.get(3))).isEqualTo(0);
    assertThat(getPhase(stoppedBeans.get(4))).isEqualTo(0);
    assertThat(getPhase(stoppedBeans.get(5))).isEqualTo(-1);
    assertThat(getPhase(stoppedBeans.get(6))).isEqualTo(Integer.MIN_VALUE);
}
Also used : Lifecycle(org.springframework.context.Lifecycle) SmartLifecycle(org.springframework.context.SmartLifecycle) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Test(org.junit.jupiter.api.Test)

Example 23 with Lifecycle

use of org.springframework.context.Lifecycle in project spring-framework by spring-projects.

the class DefaultLifecycleProcessorTests method singleLifecycleShutdown.

@Test
public void singleLifecycleShutdown() throws Exception {
    CopyOnWriteArrayList<Lifecycle> stoppedBeans = new CopyOnWriteArrayList<>();
    Lifecycle bean = new TestLifecycleBean(null, stoppedBeans);
    StaticApplicationContext context = new StaticApplicationContext();
    context.getBeanFactory().registerSingleton("bean", bean);
    context.refresh();
    assertThat(bean.isRunning()).isFalse();
    bean.start();
    assertThat(bean.isRunning()).isTrue();
    context.stop();
    assertThat(stoppedBeans.size()).isEqualTo(1);
    assertThat(bean.isRunning()).isFalse();
    assertThat(stoppedBeans.get(0)).isEqualTo(bean);
}
Also used : Lifecycle(org.springframework.context.Lifecycle) SmartLifecycle(org.springframework.context.SmartLifecycle) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Test(org.junit.jupiter.api.Test)

Example 24 with Lifecycle

use of org.springframework.context.Lifecycle in project spring-cloud-stream by spring-cloud.

the class AbstractMessageChannelBinder method doBindConsumer.

/**
 * Binds an inbound channel to a given destination. The implementation delegates to
 * {@link ProvisioningProvider#provisionConsumerDestination(String, String, ConsumerProperties)}
 * and
 * {@link #createConsumerEndpoint(ConsumerDestination, String, ConsumerProperties)}
 * for handling middleware-specific logic. If the returned consumer endpoint is an
 * {@link InitializingBean} then {@link InitializingBean#afterPropertiesSet()} will be
 * called on it. Similarly, if the returned consumer endpoint is a {@link Lifecycle},
 * then {@link Lifecycle#start()} will be called on it.
 * @param name the name of the destination
 * @param group the consumer group
 * @param inputChannel the channel to be bound
 * @param properties the {@link ConsumerProperties} of the binding
 * @return the Binding for the channel
 * @throws BinderException on internal errors during binding
 */
@Override
public final Binding<MessageChannel> doBindConsumer(String name, String group, MessageChannel inputChannel, final C properties) throws BinderException {
    MessageProducer consumerEndpoint = null;
    try {
        ConsumerDestination destination = this.provisioningProvider.provisionConsumerDestination(name, group, properties);
        if (HeaderMode.embeddedHeaders.equals(properties.getHeaderMode())) {
            enhanceMessageChannel(inputChannel);
        }
        consumerEndpoint = createConsumerEndpoint(destination, group, properties);
        consumerEndpoint.setOutputChannel(inputChannel);
        this.consumerCustomizer.configure(consumerEndpoint, name, group);
        if (consumerEndpoint instanceof InitializingBean) {
            ((InitializingBean) consumerEndpoint).afterPropertiesSet();
        }
        if (properties.isAutoStartup() && consumerEndpoint instanceof Lifecycle) {
            ((Lifecycle) consumerEndpoint).start();
        }
        Binding<MessageChannel> binding = new DefaultBinding<MessageChannel>(name, group, inputChannel, consumerEndpoint instanceof Lifecycle ? (Lifecycle) consumerEndpoint : null) {

            @Override
            public Map<String, Object> getExtendedInfo() {
                return doGetExtendedInfo(destination, properties);
            }

            @Override
            public boolean isInput() {
                return true;
            }

            @Override
            protected void afterUnbind() {
                try {
                    if (getEndpoint() instanceof DisposableBean) {
                        ((DisposableBean) getEndpoint()).destroy();
                    }
                } catch (Exception e) {
                    AbstractMessageChannelBinder.this.logger.error("Exception thrown while unbinding " + toString(), e);
                }
                afterUnbindConsumer(destination, this.group, properties);
                destroyErrorInfrastructure(destination, this.group, properties);
            }
        };
        doPublishEvent(new BindingCreatedEvent(binding));
        return binding;
    } catch (Exception e) {
        if (consumerEndpoint instanceof Lifecycle) {
            ((Lifecycle) consumerEndpoint).stop();
        }
        if (e instanceof BinderException) {
            throw (BinderException) e;
        } else if (e instanceof ProvisioningException) {
            throw (ProvisioningException) e;
        } else {
            throw new BinderException("Exception thrown while starting consumer: ", e);
        }
    }
}
Also used : Lifecycle(org.springframework.context.Lifecycle) ConsumerDestination(org.springframework.cloud.stream.provisioning.ConsumerDestination) ProvisioningException(org.springframework.cloud.stream.provisioning.ProvisioningException) IOException(java.io.IOException) FluxMessageChannel(org.springframework.integration.channel.FluxMessageChannel) AbstractMessageChannel(org.springframework.integration.channel.AbstractMessageChannel) MessageChannel(org.springframework.messaging.MessageChannel) DisposableBean(org.springframework.beans.factory.DisposableBean) ProvisioningException(org.springframework.cloud.stream.provisioning.ProvisioningException) MessageProducer(org.springframework.integration.core.MessageProducer) InitializingBean(org.springframework.beans.factory.InitializingBean)

Example 25 with Lifecycle

use of org.springframework.context.Lifecycle in project spring-cloud-stream by spring-cloud.

the class AbstractMessageChannelBinderTests method testEndpointLifecycle.

@Test
@SuppressWarnings("unchecked")
public void testEndpointLifecycle() throws Exception {
    // @checkstyle:off
    AbstractMessageChannelBinder<ConsumerProperties, ProducerProperties, ProvisioningProvider<ConsumerProperties, ProducerProperties>> binder = this.context.getBean(AbstractMessageChannelBinder.class);
    // @checkstyle:on
    ConsumerProperties consumerProperties = new ConsumerProperties();
    // to force error infrastructure creation
    consumerProperties.setMaxAttempts(1);
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("foo", "fooGroup", new DirectChannel(), consumerProperties);
    DirectFieldAccessor consumerBindingAccessor = new DirectFieldAccessor(consumerBinding);
    MessageProducer messageProducer = (MessageProducer) consumerBindingAccessor.getPropertyValue("lifecycle");
    assertThat(((Lifecycle) messageProducer).isRunning()).isTrue();
    assertThat(messageProducer.getOutputChannel()).isNotNull();
    SubscribableChannel errorChannel = (SubscribableChannel) consumerBindingAccessor.getPropertyValue("lifecycle.errorChannel");
    assertThat(errorChannel).isNotNull();
    Set<MessageHandler> handlers = TestUtils.getPropertyValue(errorChannel, "dispatcher.handlers", Set.class);
    assertThat(handlers.size()).isEqualTo(2);
    Iterator<MessageHandler> iterator = handlers.iterator();
    assertThat(iterator.next()).isInstanceOf(BridgeHandler.class);
    assertThat(iterator.next()).isInstanceOf(LastSubscriberMessageHandler.class);
    assertThat(this.context.containsBean("foo.fooGroup.errors")).isTrue();
    assertThat(this.context.containsBean("foo.fooGroup.errors.recoverer")).isTrue();
    assertThat(this.context.containsBean("foo.fooGroup.errors.handler")).isTrue();
    assertThat(this.context.containsBean("foo.fooGroup.errors.bridge")).isTrue();
    consumerBinding.unbind();
    assertThat(this.context.containsBean("foo.fooGroup.errors")).isFalse();
    assertThat(this.context.containsBean("foo.fooGroup.errors.recoverer")).isFalse();
    assertThat(this.context.containsBean("foo.fooGroup.errors.handler")).isFalse();
    assertThat(this.context.containsBean("foo.fooGroup.errors.bridge")).isFalse();
    assertThat(((Lifecycle) messageProducer).isRunning()).isFalse();
    ProducerProperties producerProps = new ProducerProperties();
    producerProps.setErrorChannelEnabled(true);
    Binding<MessageChannel> producerBinding = binder.bindProducer("bar", new DirectChannel(), producerProps);
    assertThat(this.context.containsBean("bar.errors")).isTrue();
    assertThat(this.context.containsBean("bar.errors.bridge")).isTrue();
    producerBinding.unbind();
    assertThat(this.context.containsBean("bar.errors")).isFalse();
    assertThat(this.context.containsBean("bar.errors.bridge")).isFalse();
}
Also used : MessageHandler(org.springframework.messaging.MessageHandler) DirectChannel(org.springframework.integration.channel.DirectChannel) Lifecycle(org.springframework.context.Lifecycle) MessageChannel(org.springframework.messaging.MessageChannel) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) ProvisioningProvider(org.springframework.cloud.stream.provisioning.ProvisioningProvider) MessageProducer(org.springframework.integration.core.MessageProducer) SubscribableChannel(org.springframework.messaging.SubscribableChannel) Test(org.junit.Test)

Aggregations

Lifecycle (org.springframework.context.Lifecycle)25 SmartLifecycle (org.springframework.context.SmartLifecycle)6 MessageChannel (org.springframework.messaging.MessageChannel)6 Test (org.junit.Test)4 MessageProducer (org.springframework.integration.core.MessageProducer)4 LinkedHashMap (java.util.LinkedHashMap)3 DirectFieldAccessor (org.springframework.beans.DirectFieldAccessor)3 MessageHandler (org.springframework.messaging.MessageHandler)3 IOException (java.io.IOException)2 Method (java.lang.reflect.Method)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)2 AtomicLong (java.util.concurrent.atomic.AtomicLong)2 JMException (javax.management.JMException)2 Before (org.junit.Before)2 Test (org.junit.jupiter.api.Test)2 TargetSource (org.springframework.aop.TargetSource)2 Advised (org.springframework.aop.framework.Advised)2