java类org.springframework.context.ApplicationListener的实例源码

SpringApplicationTests.java 文件源码 项目:https-github.com-g0t4-jenkins2-course-spring-boot 阅读 22 收藏 0 点赞 0 评论 0
@Test
public void contextRefreshedEventListener() throws Exception {
    SpringApplication application = new SpringApplication(ExampleConfig.class);
    application.setWebEnvironment(false);
    final AtomicReference<ApplicationContext> reference = new AtomicReference<ApplicationContext>();
    class InitializerListener implements ApplicationListener<ContextRefreshedEvent> {
        @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
            reference.set(event.getApplicationContext());
        }
    }
    application.setListeners(Arrays.asList(new InitializerListener()));
    this.context = application.run("--foo=bar");
    assertThat(this.context).isSameAs(reference.get());
    // Custom initializers do not switch off the defaults
    assertThat(getEnvironment().getProperty("foo")).isEqualTo("bar");
}
SpringApplicationTests.java 文件源码 项目:https-github.com-g0t4-jenkins2-course-spring-boot 阅读 25 收藏 0 点赞 0 评论 0
@Test
public void eventsOrder() {
    SpringApplication application = new SpringApplication(ExampleConfig.class);
    application.setWebEnvironment(false);
    final List<ApplicationEvent> events = new ArrayList<ApplicationEvent>();
    class ApplicationRunningEventListener
            implements ApplicationListener<ApplicationEvent> {
        @Override
        public void onApplicationEvent(ApplicationEvent event) {
            events.add((event));
        }
    }
    application.addListeners(new ApplicationRunningEventListener());
    this.context = application.run();
    assertThat(events).hasSize(5);
    assertThat(events.get(0)).isInstanceOf(ApplicationStartedEvent.class);
    assertThat(events.get(1)).isInstanceOf(ApplicationEnvironmentPreparedEvent.class);
    assertThat(events.get(2)).isInstanceOf(ApplicationPreparedEvent.class);
    assertThat(events.get(3)).isInstanceOf(ContextRefreshedEvent.class);
    assertThat(events.get(4)).isInstanceOf(ApplicationReadyEvent.class);
}
SpringApplicationTests.java 文件源码 项目:https-github.com-g0t4-jenkins2-course-spring-boot 阅读 24 收藏 0 点赞 0 评论 0
@Test
public void registerListener() throws Exception {
    SpringApplication application = new SpringApplication(ExampleConfig.class,
            ListenerConfig.class);
    application.setApplicationContextClass(SpyApplicationContext.class);
    final LinkedHashSet<ApplicationEvent> events = new LinkedHashSet<ApplicationEvent>();
    application.addListeners(new ApplicationListener<ApplicationEvent>() {

        @Override
        public void onApplicationEvent(ApplicationEvent event) {
            events.add(event);
        }

    });
    this.context = application.run();
    assertThat(events).hasAtLeastOneElementOfType(ApplicationPreparedEvent.class);
    assertThat(events).hasAtLeastOneElementOfType(ContextRefreshedEvent.class);
    verifyTestListenerEvents();
}
SpringApplicationTests.java 文件源码 项目:https-github.com-g0t4-jenkins2-course-spring-boot 阅读 39 收藏 0 点赞 0 评论 0
@Test
public void webEnvironmentSwitchedOffInListener() throws Exception {
    TestSpringApplication application = new TestSpringApplication(
            ExampleConfig.class);
    application.addListeners(
            new ApplicationListener<ApplicationEnvironmentPreparedEvent>() {

                @Override
                public void onApplicationEvent(
                        ApplicationEnvironmentPreparedEvent event) {
                    assertThat(event.getEnvironment())
                            .isInstanceOf(StandardServletEnvironment.class);
                    TestPropertySourceUtils.addInlinedPropertiesToEnvironment(
                            event.getEnvironment(), "foo=bar");
                    event.getSpringApplication().setWebEnvironment(false);
                }

            });
    this.context = application.run();
    assertThat(this.context.getEnvironment())
            .isNotInstanceOf(StandardServletEnvironment.class);
    assertThat(this.context.getEnvironment().getProperty("foo"));
    assertThat(this.context.getEnvironment().getPropertySources().iterator().next()
            .getName()).isEqualTo(
                    TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME);
}
AbstractApplicationContext.java 文件源码 项目:spring 阅读 24 收藏 0 点赞 0 评论 0
/**
 * Add beans that implement ApplicationListener as listeners.
 * Doesn't affect other listeners, which can be added without being beans.
 */
protected void registerListeners() {
    // Register statically specified listeners first.
    for (ApplicationListener<?> listener : getApplicationListeners()) {
        getApplicationEventMulticaster().addApplicationListener(listener);
    }

    // Do not initialize FactoryBeans here: We need to leave all regular beans
    // uninitialized to let post-processors apply to them!
    String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
    for (String listenerBeanName : listenerBeanNames) {
        getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
    }

    // Publish early application events now that we finally have a multicaster...
    Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
    this.earlyApplicationEvents = null;
    if (earlyEventsToProcess != null) {
        for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
            getApplicationEventMulticaster().multicastEvent(earlyEvent);
        }
    }
}
PostProcessorRegistrationDelegate.java 文件源码 项目:spring 阅读 29 收藏 0 点赞 0 评论 0
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
    if (this.applicationContext != null && bean instanceof ApplicationListener) {
        // potentially not detected as a listener by getBeanNamesForType retrieval
        Boolean flag = this.singletonNames.get(beanName);
        if (Boolean.TRUE.equals(flag)) {
            // singleton bean (top-level or inner): register on the fly
            this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
        }
        else if (flag == null) {
            if (logger.isWarnEnabled() && !this.applicationContext.containsBean(beanName)) {
                // inner bean with other scope - can't reliably process events
                logger.warn("Inner bean '" + beanName + "' implements ApplicationListener interface " +
                        "but is not reachable for event multicasting by its containing ApplicationContext " +
                        "because it does not have singleton scope. Only top-level listener beans are allowed " +
                        "to be of non-singleton scope.");
            }
            this.singletonNames.put(beanName, Boolean.FALSE);
        }
    }
    return bean;
}
SpringApplicationAdminMXBeanRegistrarTests.java 文件源码 项目:spring-boot-concourse 阅读 18 收藏 0 点赞 0 评论 0
@Test
public void validateReadyFlag() {
    final ObjectName objectName = createObjectName(OBJECT_NAME);
    SpringApplication application = new SpringApplication(Config.class);
    application.setWebEnvironment(false);
    application.addListeners(new ApplicationListener<ContextRefreshedEvent>() {
        @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
            try {
                assertThat(isApplicationReady(objectName)).isFalse();
            }
            catch (Exception ex) {
                throw new IllegalStateException(
                        "Could not contact spring application admin bean", ex);
            }
        }
    });
    this.context = application.run();
    assertThat(isApplicationReady(objectName)).isTrue();
}
SpringApplicationTests.java 文件源码 项目:spring-boot-concourse 阅读 22 收藏 0 点赞 0 评论 0
@Test
public void registerListener() throws Exception {
    SpringApplication application = new SpringApplication(ExampleConfig.class,
            ListenerConfig.class);
    application.setApplicationContextClass(SpyApplicationContext.class);
    final LinkedHashSet<ApplicationEvent> events = new LinkedHashSet<ApplicationEvent>();
    application.addListeners(new ApplicationListener<ApplicationEvent>() {

        @Override
        public void onApplicationEvent(ApplicationEvent event) {
            events.add(event);
        }

    });
    this.context = application.run();
    assertThat(events).hasAtLeastOneElementOfType(ApplicationPreparedEvent.class);
    assertThat(events).hasAtLeastOneElementOfType(ContextRefreshedEvent.class);
    verifyTestListenerEvents();
}
SimpleApplicationEventMulticaster.java 文件源码 项目:spring 阅读 23 收藏 0 点赞 0 评论 0
@Override
public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) {
    ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
    for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
        Executor executor = getTaskExecutor();
        if (executor != null) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    invokeListener(listener, event);
                }
            });
        }
        else {
            invokeListener(listener, event);
        }
    }
}
PersistentApplicationEventMulticaster.java 文件源码 项目:spring-domain-events 阅读 29 收藏 0 点赞 0 评论 0
private static boolean isTransactionalApplicationEventListener(ApplicationListener<?> listener) {

        Class<?> targetClass = AopUtils.getTargetClass(listener);

        if (!ApplicationListenerMethodAdapter.class.isAssignableFrom(targetClass)) {
            return false;
        }

        Field field = ReflectionUtils.findField(ApplicationListenerMethodAdapter.class, "method");
        ReflectionUtils.makeAccessible(field);
        Method method = (Method) ReflectionUtils.getField(field, listener);

        return AnnotatedElementUtils.hasAnnotation(method, TransactionalEventListener.class);
    }


问题


面经


文章

微信
公众号

扫码关注公众号