Java 类org.springframework.context.ApplicationListener 实例源码
项目:spring4-understanding
文件:SimpleApplicationEventMulticaster.java
/**
* Invoke the given listener with the given event.
* @param listener the ApplicationListener to invoke
* @param event the current event to propagate
* @since 4.1
*/
@SuppressWarnings({"unchecked", "rawtypes"})
protected void invokeListener(ApplicationListener listener, ApplicationEvent event) {
ErrorHandler errorHandler = getErrorHandler();
if (errorHandler != null) {
try {
listener.onApplicationEvent(event);
}
catch (Throwable err) {
errorHandler.handleError(err);
}
}
else {
listener.onApplicationEvent(event);
}
}
项目:alfresco-repository
文件:SafeApplicationEventMulticaster.java
@SuppressWarnings("unchecked")
protected void multicastEventInternal(final ApplicationEvent event) {
for (final ApplicationListener listener : getApplicationListeners(event)) {
Executor executor = getTaskExecutor();
if (executor != null) {
executor.execute(new Runnable() {
public void run() {
listener.onApplicationEvent(event);
}
});
}
else {
listener.onApplicationEvent(event);
}
}
}
项目:lams
文件:SimpleApplicationEventMulticaster.java
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public void multicastEvent(final ApplicationEvent event) {
for (final ApplicationListener listener : getApplicationListeners(event)) {
Executor executor = getTaskExecutor();
if (executor != null) {
executor.execute(new Runnable() {
@Override
public void run() {
listener.onApplicationEvent(event);
}
});
}
else {
listener.onApplicationEvent(event);
}
}
}
项目:spring
文件:SimpleApplicationEventMulticaster.java
/**
* Invoke the given listener with the given event.
* @param listener the ApplicationListener to invoke
* @param event the current event to propagate
* @since 4.1
*/
@SuppressWarnings({"unchecked", "rawtypes"})
protected void invokeListener(ApplicationListener listener, ApplicationEvent event) {
ErrorHandler errorHandler = getErrorHandler();
if (errorHandler != null) {
try {
listener.onApplicationEvent(event);
}
catch (Throwable err) {
errorHandler.handleError(err);
}
}
else {
try {
listener.onApplicationEvent(event);
}
catch (ClassCastException ex) {
// Possibly a lambda-defined listener which we could not resolve the generic event type for
LogFactory.getLog(getClass()).debug("Non-matching event type for listener: " + listener, ex);
}
}
}
项目:spring-domain-events
文件:PersistentApplicationEventMulticaster.java
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public void multicastEvent(ApplicationEvent event, ResolvableType eventType) {
ResolvableType type = eventType == null ? ResolvableType.forInstance(event) : eventType;
Collection<ApplicationListener<?>> listeners = getApplicationListeners(event, type);
if (listeners.isEmpty()) {
return;
}
List<ApplicationListener<?>> transactionalListeners = listeners.stream()//
.filter(PersistentApplicationEventMulticaster::isTransactionalApplicationEventListener)//
.collect(Collectors.toList());
if (!transactionalListeners.isEmpty()) {
Object eventToPersist = getEventToPersist(event);
registry.getObject().store(eventToPersist, transactionalListeners);
// EventStore.persist(eventThis)
// SpringMVC Controller Atom Feed
}
for (ApplicationListener listener : listeners) {
listener.onApplicationEvent(event);
}
}
项目:alfresco-repository
文件:IndexInfo.java
private void notifyListeners(String description, int count)
{
if (!this.applicationListeners.isEmpty())
{
IndexEvent event = new IndexEvent(this, description, count);
for (ApplicationListener listener : this.applicationListeners)
{
listener.onApplicationEvent(event);
}
}
}
项目:alfresco-repository
文件:DefaultPropertyBackedBeanRegistry.java
/**
* Broadcast event.
*
* @param event
* the event
*/
private void broadcastEvent(PropertyBackedBeanEvent event)
{
// If the system is up and running, broadcast the event immediately
if (this.isSchemaAvailable && this.wasDictionaryBootstrapped)
{
// If we have a transaction, the changed properties in it should be updated earlier,
// then the bean restart message will be sent to other node
// see ALF-20066
if (AlfrescoTransactionSupport.getTransactionId() != null &&
(event instanceof PropertyBackedBeanStartedEvent ||
event instanceof PropertyBackedBeanStoppedEvent))
{
this.afterTransactionEvents.add(event);
AlfrescoTransactionSupport.bindListener(this);
}
else
{
for (ApplicationListener listener : this.listeners)
{
listener.onApplicationEvent(event);
}
}
}
// Otherwise, defer broadcasting until the schema available event is handled
else
{
this.deferredEvents.add(event);
}
}
项目:alfresco-repository
文件:DefaultPropertyBackedBeanRegistry.java
@Override
public void afterCommit()
{
for (ApplicationEvent event : this.afterTransactionEvents)
{
for (ApplicationListener listener : this.listeners)
{
listener.onApplicationEvent(event);
}
}
this.afterTransactionEvents.clear();
}
项目:lams
文件:PostProcessorRegistrationDelegate.java
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (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;
}
项目:flow-platform
文件:PluginServiceTest.java
@Test
public void should_stop_success_demo_first() throws Throwable {
cleanFolder("flowCliE");
CountDownLatch countDownLatch = new CountDownLatch(1);
applicationEventMulticaster.addApplicationListener((ApplicationListener<PluginStatusChangeEvent>) event -> {
if (ImmutableMultiset.of(PluginStatus.INSTALLING).contains(event.getPluginStatus())) {
countDownLatch.countDown();
}
});
pluginService.install("flowCliE");
countDownLatch.await(30, TimeUnit.SECONDS);
pluginService.stop("flowCliE");
Plugin plugin = pluginDao.get("flowCliE");
Assert.assertEquals(PluginStatus.PENDING, plugin.getStatus());
Assert.assertEquals(false, plugin.getStopped());
}
项目:SkyEye
文件:Launcher.java
public static void main(String[] args) throws InterruptedException {
SpringApplicationBuilder builder = new SpringApplicationBuilder(Launcher.class);
Set<ApplicationListener<?>> listeners = builder.application().getListeners();
for (Iterator<ApplicationListener<?>> it = listeners.iterator(); it.hasNext();) {
ApplicationListener<?> listener = it.next();
if (listener instanceof LoggingApplicationListener) {
it.remove();
}
}
builder.application().setListeners(listeners);
builder.run(args);
LOGGER.info("hi-log-log4j2 start successfully");
String a = "哈哈";
while (true) {
LOGGER.info("i am test, {}", a);
Thread.sleep(1000);
}
}
项目:SkyEye
文件:Launcher.java
public static void main(String[] args) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(Launcher.class);
Set<ApplicationListener<?>> listeners = builder.application().getListeners();
for (Iterator<ApplicationListener<?>> it = listeners.iterator(); it.hasNext();) {
ApplicationListener<?> listener = it.next();
if (listener instanceof LoggingApplicationListener) {
it.remove();
}
}
builder.application().setListeners(listeners);
ConfigurableApplicationContext context = builder.run(args);
LOGGER.info("collector trace start successfully");
KafkaConsumer kafkaConsumer = (KafkaConsumer<byte[], String>) context.getBean("kafkaConsumer");
Task task = (Task) context.getBean("rpcTraceTask");
// 优雅停止项目
Runtime.getRuntime().addShutdownHook(new ShutdownHookRunner(kafkaConsumer, task));
task.doTask();
}
项目:SkyEye
文件:Launcher.java
public static void main(String[] args) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(Launcher.class);
Set<ApplicationListener<?>> listeners = builder.application().getListeners();
for (Iterator<ApplicationListener<?>> it = listeners.iterator(); it.hasNext();) {
ApplicationListener<?> listener = it.next();
if (listener instanceof LoggingApplicationListener) {
it.remove();
}
}
builder.application().setListeners(listeners);
ConfigurableApplicationContext context = builder.run(args);
LOGGER.info("collector indexer start successfully");
KafkaConsumer kafkaConsumer = (KafkaConsumer<byte[], String>) context.getBean("kafkaConsumer");
Task task = (Task) context.getBean("indexerTask");
// 优雅停止项目
Runtime.getRuntime().addShutdownHook(new ShutdownHookRunner(kafkaConsumer, task));
task.doTask();
}
项目:SkyEye
文件:Launcher.java
public static void main(String[] args) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(Launcher.class);
Set<ApplicationListener<?>> listeners = builder.application().getListeners();
for (Iterator<ApplicationListener<?>> it = listeners.iterator(); it.hasNext();) {
ApplicationListener<?> listener = it.next();
if (listener instanceof LoggingApplicationListener) {
it.remove();
}
}
builder.application().setListeners(listeners);
ConfigurableApplicationContext context = builder.run(args);
LOGGER.info("collector backup start successfully");
KafkaConsumer kafkaConsumer = (KafkaConsumer<byte[], String>) context.getBean("kafkaConsumer");
Task task = (Task) context.getBean("backupTask");
// 优雅停止项目
Runtime.getRuntime().addShutdownHook(new ShutdownHookRunner(kafkaConsumer, task));
task.doTask();
}
项目:SkyEye
文件:Launcher.java
public static void main(String[] args) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(Launcher.class);
Set<ApplicationListener<?>> listeners = builder.application().getListeners();
for (Iterator<ApplicationListener<?>> it = listeners.iterator(); it.hasNext();) {
ApplicationListener<?> listener = it.next();
if (listener instanceof LoggingApplicationListener) {
it.remove();
}
}
builder.application().setListeners(listeners);
ConfigurableApplicationContext context = builder.run(args);
LOGGER.info("collector metrics start successfully");
KafkaConsumer kafkaConsumer = (KafkaConsumer<byte[], String>) context.getBean("kafkaConsumer");
Task task = (Task) context.getBean("metricsTask");
// 优雅停止项目
Runtime.getRuntime().addShutdownHook(new ShutdownHookRunner(kafkaConsumer, task));
task.doTask();
}
项目:spring4-understanding
文件:AbstractApplicationContext.java
/**
* 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);
}
}
}
项目:spring4-understanding
文件:PostProcessorRegistrationDelegate.java
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (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;
}
项目:spring-boot-concourse
文件:SpringApplicationTests.java
@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");
}
项目:spring4-understanding
文件:SimpleApplicationEventMulticaster.java
@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);
}
}
}
项目:spring4-understanding
文件:ApplicationContextEventTests.java
private void multicastEvent(boolean match, Class<?> listenerType, ApplicationEvent event, ResolvableType eventType) {
@SuppressWarnings("unchecked")
ApplicationListener<ApplicationEvent> listener =
(ApplicationListener<ApplicationEvent>) mock(listenerType);
SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster();
smc.addApplicationListener(listener);
if (eventType != null) {
smc.multicastEvent(event, eventType);
}
else {
smc.multicastEvent(event);
}
int invocation = match ? 1 : 0;
verify(listener, times(invocation)).onApplicationEvent(event);
}
项目:spring4-understanding
文件:ApplicationContextEventTests.java
@Test
public void simpleApplicationEventMulticasterWithTaskExecutor() {
@SuppressWarnings("unchecked")
ApplicationListener<ApplicationEvent> listener = mock(ApplicationListener.class);
ApplicationEvent evt = new ContextClosedEvent(new StaticApplicationContext());
SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster();
smc.setTaskExecutor(new Executor() {
@Override
public void execute(Runnable command) {
command.run();
command.run();
}
});
smc.addApplicationListener(listener);
smc.multicastEvent(evt);
verify(listener, times(2)).onApplicationEvent(evt);
}
项目:spring4-understanding
文件:ApplicationContextEventTests.java
@Test
public void simpleApplicationEventMulticasterWithException() {
@SuppressWarnings("unchecked")
ApplicationListener<ApplicationEvent> listener = mock(ApplicationListener.class);
ApplicationEvent evt = new ContextClosedEvent(new StaticApplicationContext());
SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster();
smc.addApplicationListener(listener);
RuntimeException thrown = new RuntimeException();
willThrow(thrown).given(listener).onApplicationEvent(evt);
try {
smc.multicastEvent(evt);
fail("Should have thrown RuntimeException");
}
catch (RuntimeException ex) {
assertSame(thrown, ex);
}
}
项目:spring-boot-concourse
文件:SpringApplicationTests.java
@Test
public void applicationRunningEventListener() {
SpringApplication application = new SpringApplication(ExampleConfig.class);
application.setWebEnvironment(false);
final AtomicReference<SpringApplication> reference = new AtomicReference<SpringApplication>();
class ApplicationReadyEventListener
implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
reference.set(event.getSpringApplication());
}
}
application.addListeners(new ApplicationReadyEventListener());
this.context = application.run("--foo=bar");
assertThat(application).isSameAs(reference.get());
}
项目:spring-boot-concourse
文件:SpringApplicationTests.java
@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);
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot
文件:DelegatingApplicationListener.java
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
List<ApplicationListener<ApplicationEvent>> delegates = getListeners(
((ApplicationEnvironmentPreparedEvent) event).getEnvironment());
if (delegates.isEmpty()) {
return;
}
this.multicaster = new SimpleApplicationEventMulticaster();
for (ApplicationListener<ApplicationEvent> listener : delegates) {
this.multicaster.addApplicationListener(listener);
}
}
if (this.multicaster != null) {
this.multicaster.multicastEvent(event);
}
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot
文件:DelegatingApplicationListener.java
@SuppressWarnings("unchecked")
private List<ApplicationListener<ApplicationEvent>> getListeners(
ConfigurableEnvironment env) {
String classNames = env.getProperty(PROPERTY_NAME);
List<ApplicationListener<ApplicationEvent>> listeners = new ArrayList<ApplicationListener<ApplicationEvent>>();
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;
}
项目:spring-boot-concourse
文件:DelegatingApplicationListener.java
@SuppressWarnings("unchecked")
private List<ApplicationListener<ApplicationEvent>> getListeners(
ConfigurableEnvironment env) {
String classNames = env.getProperty(PROPERTY_NAME);
List<ApplicationListener<ApplicationEvent>> listeners = new ArrayList<ApplicationListener<ApplicationEvent>>();
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;
}
项目:spring-boot-concourse
文件:SpringApplicationTests.java
@Test
public void registerListenerWithCustomMulticaster() throws Exception {
SpringApplication application = new SpringApplication(ExampleConfig.class,
ListenerConfig.class, Multicaster.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();
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot
文件:SpringApplicationAdminMXBeanRegistrarTests.java
@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();
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot
文件:SpringApplicationTests.java
@Test
public void applicationRunningEventListener() {
SpringApplication application = new SpringApplication(ExampleConfig.class);
application.setWebEnvironment(false);
final AtomicReference<SpringApplication> reference = new AtomicReference<SpringApplication>();
class ApplicationReadyEventListener
implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
reference.set(event.getSpringApplication());
}
}
application.addListeners(new ApplicationReadyEventListener());
this.context = application.run("--foo=bar");
assertThat(application).isSameAs(reference.get());
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot
文件:SpringApplicationTests.java
@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");
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot
文件:SpringApplicationTests.java
@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);
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot
文件:SpringApplicationTests.java
@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();
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot
文件:SpringApplicationTests.java
@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);
}
项目:spring
文件:AbstractApplicationContext.java
/**
* 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);
}
}
}
项目:spring
文件:PostProcessorRegistrationDelegate.java
@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;
}
项目:spring-boot-concourse
文件:SpringApplicationAdminMXBeanRegistrarTests.java
@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();
}
项目:spring-boot-concourse
文件:SpringApplicationTests.java
@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();
}
项目:spring
文件:SimpleApplicationEventMulticaster.java
@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);
}
}
}
项目:spring-domain-events
文件:PersistentApplicationEventMulticaster.java
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);
}