add context refreshed event sample · panjf2008/JavaSpringBootSamples@269f190 · GitHub
Skip to content

Commit 269f190

Browse files
committed
add context refreshed event sample
1 parent 2612a44 commit 269f190

4 files changed

Lines changed: 70 additions & 4 deletions

File tree

‎springboot-source-code-analysis/(5)监听器设计模式.md‎

Lines changed: 2 additions & 0 deletions

‎springboot-source-code-analysis/pom.xml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,12 @@
3030
<groupId>org.springframework.boot</groupId>
3131
<artifactId>spring-boot-starter-web</artifactId>
3232
</dependency>
33+
<dependency>
34+
<groupId>junit</groupId>
35+
<artifactId>junit</artifactId>
36+
<version>4.12</version>
37+
<scope>test</scope>
38+
</dependency>
3339
</dependencies>
3440

3541
<build>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.example.springboot.source.code.analysis.listener;
2+
3+
import org.springframework.context.ApplicationContext;
4+
import org.springframework.context.ApplicationListener;
5+
import org.springframework.context.event.ContextRefreshedEvent;
6+
import org.springframework.core.annotation.Order;
7+
import org.springframework.lang.Nullable;
8+
import org.springframework.stereotype.Component;
9+
10+
/**
11+
* Created by ipipman on 2021/9/21.
12+
*
13+
* @version V1.0
14+
* @Package com.example.springboot.source.code.analysis.listener
15+
* @Description: (用一句话描述该文件做什么)
16+
* @date 2021/9/21 5:49 下午
17+
*/
18+
@Component
19+
@Order(1)
20+
public class ApplicationContextContainer implements ApplicationListener<ContextRefreshedEvent> {
21+
22+
private ApplicationContext applicationContext;
23+
24+
private static ApplicationContextContainer applicationContextContainer;
25+
26+
@Override
27+
public void onApplicationEvent(@Nullable ContextRefreshedEvent event) {
28+
if (event != null && applicationContext == null) {
29+
synchronized (ApplicationContextContainer.class) {
30+
if (applicationContext == null) {
31+
applicationContext = event.getApplicationContext();
32+
}
33+
}
34+
}
35+
applicationContextContainer = this;
36+
}
37+
38+
public static ApplicationContextContainer getInstance() {
39+
return applicationContextContainer;
40+
}
41+
42+
public <T> T getBean(Class<T> clazz) {
43+
return applicationContext.getBean(clazz);
44+
}
45+
}

‎springboot-source-code-analysis/src/test/java/com/example/springboot/source/code/analysis/SpringbootSourceCodeAnalysisApplicationTests.java‎

Lines changed: 17 additions & 4 deletions

0 commit comments

Comments
 (0)