spring,springboot,springboot cloud生命周期

1. 概述

1.1 生命周期的重要性

生命周期管理是Spring框架的核心机制,理解Spring、SpringBoot、SpringCloud的生命周期对于深入理解框架原理、优化应用性能、解决实际问题具有重要意义。

本文内容

  • Spring生命周期:Spring Bean生命周期和容器生命周期
  • SpringBoot生命周期:SpringBoot应用启动和关闭生命周期
  • SpringCloud生命周期:SpringCloud微服务生命周期
  • Bean生命周期:Bean的创建、初始化、销毁过程
  • 应用启动流程:应用启动的完整流程
  • 应用关闭流程:应用关闭的完整流程
  • 实战案例:生命周期管理实践案例

1.2 本文内容结构

本文将从以下几个方面深入探讨生命周期:

  1. Spring Bean生命周期:Bean的完整生命周期
  2. Spring容器生命周期:容器的启动和关闭
  3. SpringBoot应用生命周期:应用启动和关闭流程
  4. SpringCloud服务生命周期:微服务生命周期管理
  5. 生命周期钩子:各种生命周期钩子的使用
  6. 实战案例:生命周期管理实践案例

2. Spring Bean生命周期

2.1 Bean生命周期流程

2.1.1 Bean生命周期阶段

Bean生命周期流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Spring Bean生命周期
public class BeanLifecycle {

// Bean生命周期阶段
public enum LifecyclePhase {
INSTANTIATION, // 实例化
POPULATE_PROPERTIES, // 属性填充
BEAN_NAME_AWARE, // BeanNameAware
BEAN_FACTORY_AWARE, // BeanFactoryAware
APPLICATION_CONTEXT_AWARE, // ApplicationContextAware
BEFORE_INIT, // 初始化前
INIT_METHOD, // 初始化方法
AFTER_INIT, // 初始化后
READY, // 就绪
BEFORE_DESTROY, // 销毁前
DESTROY_METHOD, // 销毁方法
DESTROYED // 已销毁
}

// Bean生命周期示例
@Component
public class LifecycleBean implements
BeanNameAware,
BeanFactoryAware,
ApplicationContextAware,
InitializingBean,
DisposableBean {

private String beanName;
private BeanFactory beanFactory;
private ApplicationContext applicationContext;

// 1. 实例化(构造函数)
public LifecycleBean() {
System.out.println("1. Bean实例化");
}

// 2. 属性填充(@Autowired等)
@Autowired
private DependencyService dependencyService;

// 3. BeanNameAware
@Override
public void setBeanName(String name) {
this.beanName = name;
System.out.println("3. BeanNameAware: " + name);
}

// 4. BeanFactoryAware
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
System.out.println("4. BeanFactoryAware");
}

// 5. ApplicationContextAware
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = applicationContext;
System.out.println("5. ApplicationContextAware");
}

// 6. @PostConstruct(初始化前)
@PostConstruct
public void postConstruct() {
System.out.println("6. @PostConstruct");
}

// 7. InitializingBean.afterPropertiesSet(初始化)
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("7. InitializingBean.afterPropertiesSet");
}

// 8. init-method(自定义初始化方法)
public void initMethod() {
System.out.println("8. init-method");
}

// 9. Bean就绪,可以使用

// 10. @PreDestroy(销毁前)
@PreDestroy
public void preDestroy() {
System.out.println("10. @PreDestroy");
}

// 11. DisposableBean.destroy(销毁)
@Override
public void destroy() throws Exception {
System.out.println("11. DisposableBean.destroy");
}

// 12. destroy-method(自定义销毁方法)
public void destroyMethod() {
System.out.println("12. destroy-method");
}
}
}

2.2 BeanPostProcessor

2.2.1 Bean后置处理器

BeanPostProcessor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// BeanPostProcessor
@Component
public class CustomBeanPostProcessor implements BeanPostProcessor {

// Bean初始化前处理
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("Bean初始化前: " + beanName);

// 可以在这里对Bean进行增强
if (bean instanceof LifecycleBean) {
// 对特定Bean进行处理
}

return bean;
}

// Bean初始化后处理
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("Bean初始化后: " + beanName);

// 可以在这里创建代理对象
if (bean instanceof LifecycleBean) {
// 返回代理对象
return Proxy.newProxyInstance(
bean.getClass().getClassLoader(),
bean.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
return method.invoke(bean, args);
}
}
);
}

return bean;
}
}

3. Spring容器生命周期

3.1 容器启动流程

3.1.1 容器启动

Spring容器启动流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Spring容器启动流程
public class SpringContainerLifecycle {

public void startContainer() {
// 1. 创建ApplicationContext
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 或
// ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

// 2. 容器启动流程
// 2.1 加载配置文件
// 2.2 解析Bean定义
// 2.3 注册Bean定义
// 2.4 实例化单例Bean
// 2.5 初始化Bean
// 2.6 容器就绪
}

// 容器启动监听器
@Component
public class ContainerStartListener implements ApplicationListener<ContextRefreshedEvent> {

@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println("容器启动完成");

// 容器启动后的初始化工作
ApplicationContext context = event.getApplicationContext();
// 执行启动后的逻辑
}
}
}

3.2 容器关闭流程

3.2.1 容器关闭

Spring容器关闭流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Spring容器关闭流程
public class SpringContainerShutdown {

public void shutdownContainer(ApplicationContext context) {
// 1. 发布ContextClosedEvent事件
// 2. 调用所有单例Bean的销毁方法
// 3. 关闭BeanFactory
// 4. 容器关闭完成

if (context instanceof ConfigurableApplicationContext) {
((ConfigurableApplicationContext) context).close();
}
}

// 容器关闭监听器
@Component
public class ContainerShutdownListener implements ApplicationListener<ContextClosedEvent> {

@Override
public void onApplicationEvent(ContextClosedEvent event) {
System.out.println("容器关闭");

// 容器关闭前的清理工作
// 1. 关闭线程池
// 2. 关闭连接池
// 3. 保存数据
}
}
}

4. SpringBoot应用生命周期

4.1 应用启动流程

4.1.1 SpringBoot启动流程

SpringBoot应用启动流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// SpringBoot应用启动流程
@SpringBootApplication
public class SpringBootApplicationLifecycle {

public static void main(String[] args) {
// 1. 创建SpringApplication实例
SpringApplication app = new SpringApplication(SpringBootApplicationLifecycle.class);

// 2. 设置应用属性
app.setBannerMode(Banner.Mode.OFF);

// 3. 运行应用
ConfigurableApplicationContext context = app.run(args);

// 启动流程:
// 1. 准备环境(Environment)
// 2. 打印Banner
// 3. 创建ApplicationContext
// 4. 准备ApplicationContext
// 5. 刷新ApplicationContext(加载Bean)
// 6. 执行ApplicationRunner和CommandLineRunner
// 7. 应用启动完成
}

// ApplicationRunner(应用启动后执行)
@Component
public class MyApplicationRunner implements ApplicationRunner {

@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner执行");
// 应用启动后的初始化工作
}
}

// CommandLineRunner(应用启动后执行)
@Component
public class MyCommandLineRunner implements CommandLineRunner {

@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner执行");
// 应用启动后的初始化工作
}
}
}

4.2 应用关闭流程

4.2.1 SpringBoot关闭流程

SpringBoot应用关闭流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// SpringBoot应用关闭流程
@SpringBootApplication
public class SpringBootShutdown {

public static void main(String[] args) {
ConfigurableApplicationContext context =
SpringApplication.run(SpringBootShutdown.class, args);

// 注册关闭钩子
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("应用关闭钩子执行");
context.close();
}));
}

// 优雅关闭配置
@Configuration
public class GracefulShutdownConfig {

@Bean
public TomcatServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addConnectorCustomizers(connector -> {
// 设置优雅关闭超时时间
connector.setProperty("connectionTimeout", "20000");
});
return factory;
}
}

// 关闭监听器
@Component
public class ShutdownListener implements ApplicationListener<ContextClosedEvent> {

@Override
public void onApplicationEvent(ContextClosedEvent event) {
System.out.println("应用关闭");

// 执行关闭前的清理工作
// 1. 停止接收新请求
// 2. 等待正在处理的请求完成
// 3. 关闭资源
}
}
}

4.3 生命周期事件

4.3.1 应用生命周期事件

SpringBoot生命周期事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// SpringBoot生命周期事件
public class SpringBootLifecycleEvents {

// 应用启动事件监听
@Component
public class ApplicationStartListener implements ApplicationListener<ApplicationStartedEvent> {

@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
System.out.println("应用启动事件");
}
}

// 应用就绪事件监听
@Component
public class ApplicationReadyListener implements ApplicationListener<ApplicationReadyEvent> {

@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
System.out.println("应用就绪事件");
// 应用已完全启动,可以接收请求
}
}

// 应用失败事件监听
@Component
public class ApplicationFailedListener implements ApplicationListener<ApplicationFailedEvent> {

@Override
public void onApplicationEvent(ApplicationFailedEvent event) {
System.out.println("应用启动失败");
Exception exception = event.getException();
// 处理启动失败
}
}

// 使用@EventListener注解
@Component
public class LifecycleEventListeners {

@EventListener
public void handleContextRefreshed(ContextRefreshedEvent event) {
System.out.println("Context刷新事件");
}

@EventListener
public void handleContextStarted(ContextStartedEvent event) {
System.out.println("Context启动事件");
}

@EventListener
public void handleContextStopped(ContextStoppedEvent event) {
System.out.println("Context停止事件");
}

@EventListener
public void handleContextClosed(ContextClosedEvent event) {
System.out.println("Context关闭事件");
}
}
}

5. SpringCloud服务生命周期

5.1 服务注册与发现

5.1.1 服务生命周期

SpringCloud服务生命周期

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// SpringCloud服务生命周期
@SpringBootApplication
@EnableEurekaClient
public class SpringCloudServiceLifecycle {

public static void main(String[] args) {
SpringApplication.run(SpringCloudServiceLifecycle.class, args);
}

// 服务注册监听
@Component
public class ServiceRegistrationListener {

@EventListener
public void handleInstanceRegistered(InstanceRegisteredEvent event) {
System.out.println("服务注册成功: " + event.getInstanceInfo());
}

@EventListener
public void handleInstancePreRegistered(InstancePreRegisteredEvent event) {
System.out.println("服务注册前: " + event.getInstanceInfo());
}
}

// 服务发现监听
@Component
public class ServiceDiscoveryListener {

@EventListener
public void handleServiceInstancesChanged(ServiceInstancesChangedEvent event) {
System.out.println("服务实例变更: " + event.getServiceName());
// 更新本地服务列表
}
}
}

5.2 配置中心生命周期

5.2.1 配置刷新

配置中心生命周期

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 配置中心生命周期
@SpringBootApplication
@RefreshScope
public class ConfigCenterLifecycle {

@Value("${app.name}")
private String appName;

// 配置刷新监听
@Component
public class ConfigRefreshListener {

@EventListener
public void handleEnvironmentChange(EnvironmentChangeEvent event) {
System.out.println("配置变更: " + event.getKeys());
// 处理配置变更
}
}

// 使用@RefreshScope实现配置热更新
@Component
@RefreshScope
public class RefreshableConfig {

@Value("${app.version}")
private String version;

public String getVersion() {
return version;
}
}
}

6. 生命周期钩子

6.1 启动钩子

6.1.1 启动钩子使用

启动钩子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// 启动钩子
@Component
public class StartupHooks {

// 1. @PostConstruct
@PostConstruct
public void postConstruct() {
System.out.println("@PostConstruct执行");
// 初始化工作
}

// 2. InitializingBean
@Component
public class MyInitializingBean implements InitializingBean {

@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean执行");
}
}

// 3. init-method
@Component(initMethod = "init")
public class InitMethodBean {

public void init() {
System.out.println("init-method执行");
}
}

// 4. ApplicationRunner
@Component
public class MyApplicationRunner implements ApplicationRunner {

@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner执行");
}
}

// 5. CommandLineRunner
@Component
public class MyCommandLineRunner implements CommandLineRunner {

@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner执行");
}
}
}

6.2 关闭钩子

6.2.1 关闭钩子使用

关闭钩子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 关闭钩子
@Component
public class ShutdownHooks {

// 1. @PreDestroy
@PreDestroy
public void preDestroy() {
System.out.println("@PreDestroy执行");
// 清理工作
}

// 2. DisposableBean
@Component
public class MyDisposableBean implements DisposableBean {

@Override
public void destroy() throws Exception {
System.out.println("DisposableBean执行");
}
}

// 3. destroy-method
@Component(destroyMethod = "cleanup")
public class DestroyMethodBean {

public void cleanup() {
System.out.println("destroy-method执行");
}
}

// 4. 注册JVM关闭钩子
@PostConstruct
public void registerShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("JVM关闭钩子执行");
// 清理工作
}));
}
}

7. 实战案例

7.1 完整生命周期管理

7.1.1 生命周期管理案例

完整生命周期管理案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// 完整生命周期管理案例
@SpringBootApplication
public class CompleteLifecycleManagement {

public static void main(String[] args) {
SpringApplication app = new SpringApplication(CompleteLifecycleManagement.class);

// 添加生命周期监听器
app.addListeners(new ApplicationLifecycleListener());

ConfigurableApplicationContext context = app.run(args);

// 注册关闭钩子
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("应用关闭");
context.close();
}));
}

// 应用生命周期监听器
public static class ApplicationLifecycleListener
implements ApplicationListener<ApplicationEvent> {

@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationStartingEvent) {
System.out.println("应用启动中");
} else if (event instanceof ApplicationEnvironmentPreparedEvent) {
System.out.println("环境准备完成");
} else if (event instanceof ApplicationContextInitializedEvent) {
System.out.println("ApplicationContext初始化完成");
} else if (event instanceof ApplicationPreparedEvent) {
System.out.println("应用准备完成");
} else if (event instanceof ContextRefreshedEvent) {
System.out.println("Context刷新完成");
} else if (event instanceof ApplicationStartedEvent) {
System.out.println("应用启动完成");
} else if (event instanceof ApplicationReadyEvent) {
System.out.println("应用就绪");
} else if (event instanceof ContextClosedEvent) {
System.out.println("Context关闭");
} else if (event instanceof ApplicationFailedEvent) {
System.out.println("应用启动失败");
}
}
}

// 资源管理Bean
@Component
public class ResourceManager implements InitializingBean, DisposableBean {

private ExecutorService executorService;

@Override
public void afterPropertiesSet() throws Exception {
System.out.println("初始化资源管理器");
executorService = Executors.newFixedThreadPool(10);
}

@Override
public void destroy() throws Exception {
System.out.println("关闭资源管理器");
if (executorService != null) {
executorService.shutdown();
try {
if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
executorService.shutdownNow();
}
}
}
}
}

8. 总结

8.1 核心要点

  1. Bean生命周期:实例化、属性填充、初始化、销毁的完整流程
  2. 容器生命周期:容器启动和关闭的流程
  3. 应用生命周期:SpringBoot应用启动和关闭的流程
  4. 服务生命周期:SpringCloud微服务的生命周期管理
  5. 生命周期钩子:各种生命周期钩子的使用场景
  6. 优雅关闭:应用优雅关闭的实现

8.2 关键理解

  1. 执行顺序:理解生命周期各阶段的执行顺序
  2. 钩子选择:根据需求选择合适的生命周期钩子
  3. 资源管理:在合适的生命周期阶段管理资源
  4. 优雅关闭:实现应用的优雅关闭
  5. 事件驱动:使用事件机制处理生命周期

8.3 最佳实践

  1. 合理使用钩子:根据需求选择合适的生命周期钩子
  2. 资源管理:在初始化时创建资源,在销毁时释放资源
  3. 优雅关闭:实现应用的优雅关闭,避免数据丢失
  4. 事件监听:使用事件监听器处理生命周期事件
  5. 文档记录:记录生命周期相关的配置和逻辑
  6. 测试验证:测试验证生命周期逻辑的正确性

相关文章

  • 第515集 你如何做可观测性建设?
  • [第514集 spring, springboot, springbootcloud发展历程,在企业中如何使用,为什么,好处](./第514集spring springboot springbootcloud发展历程在企业中如何使用为什么好处.md)
  • [第513集 spring,springboot,springboot cloud生命周期](./第513集spring springboot springboot cloud生命周期.md)
  • 第512集 如何定位线上慢请求?