Search in sources :

Example 11 with ApplicationEvent

use of org.springframework.context.ApplicationEvent in project spring-boot by spring-projects.

the class DelegatingApplicationListener method getListeners.

@SuppressWarnings("unchecked")
private List<ApplicationListener<ApplicationEvent>> getListeners(ConfigurableEnvironment environment) {
    if (environment == null) {
        return Collections.emptyList();
    }
    String classNames = environment.getProperty(PROPERTY_NAME);
    List<ApplicationListener<ApplicationEvent>> listeners = new ArrayList<>();
    if (StringUtils.hasLength(classNames)) {
        for (String className : StringUtils.commaDelimitedListToSet(classNames)) {
            try {
                Class<?> clazz = ClassUtils.forName(className, ClassUtils.getDefaultClassLoader());
                Assert.isAssignable(ApplicationListener.class, clazz, () -> "class [" + className + "] must implement ApplicationListener");
                listeners.add((ApplicationListener<ApplicationEvent>) BeanUtils.instantiateClass(clazz));
            } catch (Exception ex) {
                throw new ApplicationContextException("Failed to load context listener class [" + className + "]", ex);
            }
        }
    }
    AnnotationAwareOrderComparator.sort(listeners);
    return listeners;
}
Also used : ApplicationListener(org.springframework.context.ApplicationListener) ArrayList(java.util.ArrayList) ApplicationEvent(org.springframework.context.ApplicationEvent) ApplicationContextException(org.springframework.context.ApplicationContextException) ApplicationContextException(org.springframework.context.ApplicationContextException)

Example 12 with ApplicationEvent

use of org.springframework.context.ApplicationEvent in project spring-boot by spring-projects.

the class SpringApplicationTests method eventsArePublishedInExpectedOrder.

@Test
@SuppressWarnings("unchecked")
void eventsArePublishedInExpectedOrder() {
    SpringApplication application = new SpringApplication(ExampleConfig.class);
    application.setWebApplicationType(WebApplicationType.NONE);
    ApplicationListener<ApplicationEvent> listener = mock(ApplicationListener.class);
    application.addListeners(listener);
    this.context = application.run();
    InOrder inOrder = Mockito.inOrder(listener);
    then(listener).should(inOrder).onApplicationEvent(isA(ApplicationStartingEvent.class));
    then(listener).should(inOrder).onApplicationEvent(isA(ApplicationEnvironmentPreparedEvent.class));
    then(listener).should(inOrder).onApplicationEvent(isA(ApplicationContextInitializedEvent.class));
    then(listener).should(inOrder).onApplicationEvent(isA(ApplicationPreparedEvent.class));
    then(listener).should(inOrder).onApplicationEvent(isA(ContextRefreshedEvent.class));
    then(listener).should(inOrder).onApplicationEvent(isA(ApplicationStartedEvent.class));
    then(listener).should(inOrder).onApplicationEvent(argThat(isAvailabilityChangeEventWithState(LivenessState.CORRECT)));
    then(listener).should(inOrder).onApplicationEvent(isA(ApplicationReadyEvent.class));
    then(listener).should(inOrder).onApplicationEvent(argThat(isAvailabilityChangeEventWithState(ReadinessState.ACCEPTING_TRAFFIC)));
    inOrder.verifyNoMoreInteractions();
}
Also used : InOrder(org.mockito.InOrder) ApplicationReadyEvent(org.springframework.boot.context.event.ApplicationReadyEvent) ApplicationEvent(org.springframework.context.ApplicationEvent) SpringApplicationEvent(org.springframework.boot.context.event.SpringApplicationEvent) ApplicationPreparedEvent(org.springframework.boot.context.event.ApplicationPreparedEvent) ApplicationStartedEvent(org.springframework.boot.context.event.ApplicationStartedEvent) ApplicationStartingEvent(org.springframework.boot.context.event.ApplicationStartingEvent) ApplicationContextInitializedEvent(org.springframework.boot.context.event.ApplicationContextInitializedEvent) ApplicationEnvironmentPreparedEvent(org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent) ContextRefreshedEvent(org.springframework.context.event.ContextRefreshedEvent) Test(org.junit.jupiter.api.Test)

Example 13 with ApplicationEvent

use of org.springframework.context.ApplicationEvent in project spring-boot by spring-projects.

the class SpringApplicationTests method deregistersShutdownHookForFailedApplicationContext.

@Test
void deregistersShutdownHookForFailedApplicationContext() {
    SpringApplication application = new SpringApplication(BrokenPostConstructConfig.class);
    List<ApplicationEvent> events = new ArrayList<>();
    application.addListeners(events::add);
    application.setWebApplicationType(WebApplicationType.NONE);
    assertThatExceptionOfType(BeanCreationException.class).isThrownBy(application::run);
    assertThat(events).hasAtLeastOneElementOfType(ApplicationFailedEvent.class);
    ApplicationFailedEvent failure = events.stream().filter((event) -> event instanceof ApplicationFailedEvent).map(ApplicationFailedEvent.class::cast).findFirst().get();
    assertThat(SpringApplicationShutdownHookInstance.get()).didNotRegisterApplicationContext(failure.getApplicationContext());
}
Also used : ApplicationFailedEvent(org.springframework.boot.context.event.ApplicationFailedEvent) BeforeEach(org.junit.jupiter.api.BeforeEach) ArgumentMatchers(org.mockito.ArgumentMatchers) ApplicationReadyEvent(org.springframework.boot.context.event.ApplicationReadyEvent) Autowired(org.springframework.beans.factory.annotation.Autowired) ApplicationContextException(org.springframework.context.ApplicationContextException) AnnotationConfigUtils(org.springframework.context.annotation.AnnotationConfigUtils) SimpleApplicationEventMulticaster(org.springframework.context.event.SimpleApplicationEventMulticaster) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Assertions.assertThatNoException(org.assertj.core.api.Assertions.assertThatNoException) BDDMockito.given(org.mockito.BDDMockito.given) ApplicationStartedEvent(org.springframework.boot.context.event.ApplicationStartedEvent) Map(java.util.Map) AvailabilityChangeEvent(org.springframework.boot.availability.AvailabilityChangeEvent) TomcatServletWebServerFactory(org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory) Resource(org.springframework.core.io.Resource) ApplicationContextInitializedEvent(org.springframework.boot.context.event.ApplicationContextInitializedEvent) SpringApplicationBuilder(org.springframework.boot.builder.SpringApplicationBuilder) Mockito.atLeastOnce(org.mockito.Mockito.atLeastOnce) Set(java.util.Set) CachedIntrospectionResults(org.springframework.beans.CachedIntrospectionResults) ApplicationStartup(org.springframework.core.metrics.ApplicationStartup) AnnotationConfigApplicationContext(org.springframework.context.annotation.AnnotationConfigApplicationContext) ApplicationStartingEvent(org.springframework.boot.context.event.ApplicationStartingEvent) CompositePropertySource(org.springframework.core.env.CompositePropertySource) AbstractApplicationContext(org.springframework.context.support.AbstractApplicationContext) BeanNameGenerator(org.springframework.beans.factory.support.BeanNameGenerator) Lazy(org.springframework.context.annotation.Lazy) ApplicationContextAware(org.springframework.context.ApplicationContextAware) Mockito.mock(org.mockito.Mockito.mock) Ordered(org.springframework.core.Ordered) CommandLinePropertySource(org.springframework.core.env.CommandLinePropertySource) PropertySource(org.springframework.core.env.PropertySource) Mockito.spy(org.mockito.Mockito.spy) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) ApplicationEnvironmentPreparedEvent(org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) BeanCreationException(org.springframework.beans.factory.BeanCreationException) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) LinkedHashSet(java.util.LinkedHashSet) ArgumentMatchers.isA(org.mockito.ArgumentMatchers.isA) ReactiveWebApplicationContext(org.springframework.boot.web.reactive.context.ReactiveWebApplicationContext) LivenessState(org.springframework.boot.availability.LivenessState) SmartApplicationListener(org.springframework.context.event.SmartApplicationListener) MultiValueMap(org.springframework.util.MultiValueMap) Mono(reactor.core.publisher.Mono) ApplicationEvent(org.springframework.context.ApplicationEvent) ConfigurableWebEnvironment(org.springframework.web.context.ConfigurableWebEnvironment) AfterEach(org.junit.jupiter.api.AfterEach) Mockito.never(org.mockito.Mockito.never) NettyReactiveWebServerFactory(org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory) Condition(org.assertj.core.api.Condition) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) CapturedOutput(org.springframework.boot.testsupport.system.CapturedOutput) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) MockEnvironment(org.springframework.mock.env.MockEnvironment) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) AnnotationConfigServletWebServerApplicationContext(org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext) Mockito.mockingDetails(org.mockito.Mockito.mockingDetails) ApplicationPreparedEvent(org.springframework.boot.context.event.ApplicationPreparedEvent) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) BeanDefinitionRegistry(org.springframework.beans.factory.support.BeanDefinitionRegistry) ConfigurableListableBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) DefaultBeanNameGenerator(org.springframework.beans.factory.support.DefaultBeanNameGenerator) ArgumentMatcher(org.mockito.ArgumentMatcher) BeanCurrentlyInCreationException(org.springframework.beans.factory.BeanCurrentlyInCreationException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) Profiles(org.springframework.core.env.Profiles) ApplicationEventMulticaster(org.springframework.context.event.ApplicationEventMulticaster) ResourceLoader(org.springframework.core.io.ResourceLoader) BDDMockito.willThrow(org.mockito.BDDMockito.willThrow) ApplicationConversionService(org.springframework.boot.convert.ApplicationConversionService) StandardServletEnvironment(org.springframework.web.context.support.StandardServletEnvironment) WebApplicationContext(org.springframework.web.context.WebApplicationContext) ApplicationListener(org.springframework.context.ApplicationListener) ApplicationFailedEvent(org.springframework.boot.context.event.ApplicationFailedEvent) BeanDefinitionOverrideException(org.springframework.beans.factory.support.BeanDefinitionOverrideException) Test(org.junit.jupiter.api.Test) Configuration(org.springframework.context.annotation.Configuration) List(java.util.List) InstanceSupplier(org.springframework.boot.BootstrapRegistry.InstanceSupplier) TestPropertySourceUtils(org.springframework.test.context.support.TestPropertySourceUtils) Environment(org.springframework.core.env.Environment) MapPropertySource(org.springframework.core.env.MapPropertySource) PostConstruct(javax.annotation.PostConstruct) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) AnnotationConfigReactiveWebServerApplicationContext(org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext) ClassPathResource(org.springframework.core.io.ClassPathResource) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) UnsatisfiedDependencyException(org.springframework.beans.factory.UnsatisfiedDependencyException) ObjectProvider(org.springframework.beans.factory.ObjectProvider) ArgumentCaptor(org.mockito.ArgumentCaptor) StaticApplicationContext(org.springframework.context.support.StaticApplicationContext) OutputCaptureExtension(org.springframework.boot.testsupport.system.OutputCaptureExtension) DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader) Assertions.assertThatIllegalStateException(org.assertj.core.api.Assertions.assertThatIllegalStateException) ReadinessState(org.springframework.boot.availability.ReadinessState) InOrder(org.mockito.InOrder) Iterator(java.util.Iterator) BDDMockito.then(org.mockito.BDDMockito.then) StandardEnvironment(org.springframework.core.env.StandardEnvironment) AvailabilityState(org.springframework.boot.availability.AvailabilityState) StartupStep(org.springframework.core.metrics.StartupStep) ApplicationContext(org.springframework.context.ApplicationContext) SpringApplicationEvent(org.springframework.boot.context.event.SpringApplicationEvent) Mockito(org.mockito.Mockito) ContextRefreshedEvent(org.springframework.context.event.ContextRefreshedEvent) HttpHandler(org.springframework.http.server.reactive.HttpHandler) Bean(org.springframework.context.annotation.Bean) Collections(java.util.Collections) ApplicationContextInitializer(org.springframework.context.ApplicationContextInitializer) StringUtils(org.springframework.util.StringUtils) BeanCreationException(org.springframework.beans.factory.BeanCreationException) ApplicationEvent(org.springframework.context.ApplicationEvent) SpringApplicationEvent(org.springframework.boot.context.event.SpringApplicationEvent) ArrayList(java.util.ArrayList) Test(org.junit.jupiter.api.Test)

Example 14 with ApplicationEvent

use of org.springframework.context.ApplicationEvent in project spring-boot by spring-projects.

the class SpringApplicationTests method verifyRegisteredListenerSuccessEvents.

@SuppressWarnings("unchecked")
private void verifyRegisteredListenerSuccessEvents() {
    ApplicationListener<ApplicationEvent> listener = this.context.getBean("testApplicationListener", ApplicationListener.class);
    InOrder inOrder = Mockito.inOrder(listener);
    then(listener).should(inOrder).onApplicationEvent(isA(ContextRefreshedEvent.class));
    then(listener).should(inOrder).onApplicationEvent(isA(ApplicationStartedEvent.class));
    then(listener).should(inOrder).onApplicationEvent(argThat(isAvailabilityChangeEventWithState(LivenessState.CORRECT)));
    then(listener).should(inOrder).onApplicationEvent(isA(ApplicationReadyEvent.class));
    then(listener).should(inOrder).onApplicationEvent(argThat(isAvailabilityChangeEventWithState(ReadinessState.ACCEPTING_TRAFFIC)));
    inOrder.verifyNoMoreInteractions();
}
Also used : InOrder(org.mockito.InOrder) ApplicationReadyEvent(org.springframework.boot.context.event.ApplicationReadyEvent) ApplicationEvent(org.springframework.context.ApplicationEvent) SpringApplicationEvent(org.springframework.boot.context.event.SpringApplicationEvent) ApplicationStartedEvent(org.springframework.boot.context.event.ApplicationStartedEvent) ContextRefreshedEvent(org.springframework.context.event.ContextRefreshedEvent)

Example 15 with ApplicationEvent

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

the class EventPublishingTestExecutionListenerTests method assertNoEvent.

private void assertNoEvent(Class<? extends TestContextEvent> eventClass, Consumer<TestContext> callback) {
    callback.accept(testContext);
    // The listener attempted to publish the event...
    verify(testContext, times(1)).publishEvent(eventFactory.capture());
    // But the event was not actually published since the ApplicationContext
    // was not available.
    verify(applicationContext, never()).publishEvent(any());
    // In any case, we can still verify the type of event that would have
    // been published.
    ApplicationEvent event = eventFactory.getValue().apply(testContext);
    assertThat(event).isInstanceOf(eventClass);
    assertThat(event.getSource()).isEqualTo(testContext);
}
Also used : ApplicationEvent(org.springframework.context.ApplicationEvent)

Aggregations

ApplicationEvent (org.springframework.context.ApplicationEvent)44 ApplicationEventPublisher (org.springframework.context.ApplicationEventPublisher)16 Test (org.junit.Test)14 Test (org.junit.jupiter.api.Test)11 ApplicationListener (org.springframework.context.ApplicationListener)9 AtomicReference (java.util.concurrent.atomic.AtomicReference)8 ArrayList (java.util.ArrayList)7 PayloadApplicationEvent (org.springframework.context.PayloadApplicationEvent)7 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)6 ApplicationContext (org.springframework.context.ApplicationContext)6 StaticApplicationContext (org.springframework.context.support.StaticApplicationContext)6 CountDownLatch (java.util.concurrent.CountDownLatch)5 Matchers.containsString (org.hamcrest.Matchers.containsString)5 Socket (java.net.Socket)4 List (java.util.List)4 AbstractApplicationContext (org.springframework.context.support.AbstractApplicationContext)4 IOException (java.io.IOException)3 InOrder (org.mockito.InOrder)3 ApplicationReadyEvent (org.springframework.boot.context.event.ApplicationReadyEvent)3 ApplicationStartedEvent (org.springframework.boot.context.event.ApplicationStartedEvent)3