Add ApplicationListener example

This commit is contained in:
Grzegorz Piwowarek 2016-08-14 08:13:04 +02:00
parent 28f1fe27e2
commit 24e033a24b
3 changed files with 29 additions and 0 deletions

View File

@ -130,6 +130,13 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.5.1</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.hamcrest</groupId> <groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId> <artifactId>hamcrest-core</artifactId>

View File

@ -0,0 +1,16 @@
package org.baeldung.startup;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component
public class StartupApplicationListenerExample implements ApplicationListener<ContextRefreshedEvent> {
public static int counter;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
counter++;
}
}

View File

@ -1,5 +1,6 @@
package org.baeldung.startup; package org.baeldung.startup;
import org.assertj.core.api.Assertions;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCreationException;
@ -35,4 +36,9 @@ public class SpringStartupTest {
public void whenInitializingBean_shouldLogEnv() throws Exception { public void whenInitializingBean_shouldLogEnv() throws Exception {
ctx.getBean(InitializingBeanExampleBean.class); ctx.getBean(InitializingBeanExampleBean.class);
} }
@Test
public void whenApplicationListener_shouldRunOnce() throws Exception {
Assertions.assertThat(StartupApplicationListenerExample.counter).isEqualTo(1);
}
} }