第513集spring,springboot,springboot cloud生命周期
|字数总计:3.2k|阅读时长:14分钟|阅读量:
spring,springboot,springboot cloud生命周期
1. 概述
1.1 生命周期的重要性
生命周期管理是Spring框架的核心机制,理解Spring、SpringBoot、SpringCloud的生命周期对于深入理解框架原理、优化应用性能、解决实际问题具有重要意义。
本文内容:
- Spring生命周期:Spring Bean生命周期和容器生命周期
- SpringBoot生命周期:SpringBoot应用启动和关闭生命周期
- SpringCloud生命周期:SpringCloud微服务生命周期
- Bean生命周期:Bean的创建、初始化、销毁过程
- 应用启动流程:应用启动的完整流程
- 应用关闭流程:应用关闭的完整流程
- 实战案例:生命周期管理实践案例
1.2 本文内容结构
本文将从以下几个方面深入探讨生命周期:
- Spring Bean生命周期:Bean的完整生命周期
- Spring容器生命周期:容器的启动和关闭
- SpringBoot应用生命周期:应用启动和关闭流程
- SpringCloud服务生命周期:微服务生命周期管理
- 生命周期钩子:各种生命周期钩子的使用
- 实战案例:生命周期管理实践案例
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
| public class BeanLifecycle { public enum LifecyclePhase { INSTANTIATION, POPULATE_PROPERTIES, BEAN_NAME_AWARE, BEAN_FACTORY_AWARE, APPLICATION_CONTEXT_AWARE, BEFORE_INIT, INIT_METHOD, AFTER_INIT, READY, BEFORE_DESTROY, DESTROY_METHOD, DESTROYED } @Component public class LifecycleBean implements BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean, DisposableBean { private String beanName; private BeanFactory beanFactory; private ApplicationContext applicationContext; public LifecycleBean() { System.out.println("1. Bean实例化"); } @Autowired private DependencyService dependencyService; @Override public void setBeanName(String name) { this.beanName = name; System.out.println("3. BeanNameAware: " + name); } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; System.out.println("4. BeanFactoryAware"); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; System.out.println("5. ApplicationContextAware"); } @PostConstruct public void postConstruct() { System.out.println("6. @PostConstruct"); } @Override public void afterPropertiesSet() throws Exception { System.out.println("7. InitializingBean.afterPropertiesSet"); } public void initMethod() { System.out.println("8. init-method"); } @PreDestroy public void preDestroy() { System.out.println("10. @PreDestroy"); } @Override public void destroy() throws Exception { System.out.println("11. DisposableBean.destroy"); } 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
| @Component public class CustomBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("Bean初始化前: " + beanName); if (bean instanceof LifecycleBean) { } return 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
| public class SpringContainerLifecycle { public void startContainer() { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); } @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
| public class SpringContainerShutdown { public void shutdownContainer(ApplicationContext context) { if (context instanceof ConfigurableApplicationContext) { ((ConfigurableApplicationContext) context).close(); } } @Component public class ContainerShutdownListener implements ApplicationListener<ContextClosedEvent> { @Override public void onApplicationEvent(ContextClosedEvent event) { System.out.println("容器关闭"); } } }
|
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
| @SpringBootApplication public class SpringBootApplicationLifecycle { public static void main(String[] args) { SpringApplication app = new SpringApplication(SpringBootApplicationLifecycle.class); app.setBannerMode(Banner.Mode.OFF); ConfigurableApplicationContext context = app.run(args); } @Component public class MyApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("ApplicationRunner执行"); } } @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
| @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("应用关闭"); } } }
|
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
| 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(); } } @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
| @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()); } } @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 { @PostConstruct public void postConstruct() { System.out.println("@PostConstruct执行"); } @Component public class MyInitializingBean implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { System.out.println("InitializingBean执行"); } } @Component(initMethod = "init") public class InitMethodBean { public void init() { System.out.println("init-method执行"); } } @Component public class MyApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("ApplicationRunner执行"); } } @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 { @PreDestroy public void preDestroy() { System.out.println("@PreDestroy执行"); } @Component public class MyDisposableBean implements DisposableBean { @Override public void destroy() throws Exception { System.out.println("DisposableBean执行"); } } @Component(destroyMethod = "cleanup") public class DestroyMethodBean { public void cleanup() { System.out.println("destroy-method执行"); } } @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("应用启动失败"); } } } @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 核心要点
- Bean生命周期:实例化、属性填充、初始化、销毁的完整流程
- 容器生命周期:容器启动和关闭的流程
- 应用生命周期:SpringBoot应用启动和关闭的流程
- 服务生命周期:SpringCloud微服务的生命周期管理
- 生命周期钩子:各种生命周期钩子的使用场景
- 优雅关闭:应用优雅关闭的实现
8.2 关键理解
- 执行顺序:理解生命周期各阶段的执行顺序
- 钩子选择:根据需求选择合适的生命周期钩子
- 资源管理:在合适的生命周期阶段管理资源
- 优雅关闭:实现应用的优雅关闭
- 事件驱动:使用事件机制处理生命周期
8.3 最佳实践
- 合理使用钩子:根据需求选择合适的生命周期钩子
- 资源管理:在初始化时创建资源,在销毁时释放资源
- 优雅关闭:实现应用的优雅关闭,避免数据丢失
- 事件监听:使用事件监听器处理生命周期事件
- 文档记录:记录生命周期相关的配置和逻辑
- 测试验证:测试验证生命周期逻辑的正确性
相关文章:
- 第515集 你如何做可观测性建设?
- [第514集 spring, springboot, springbootcloud发展历程,在企业中如何使用,为什么,好处](./第514集spring springboot springbootcloud发展历程在企业中如何使用为什么好处.md)
- [第513集 spring,springboot,springboot cloud生命周期](./第513集spring springboot springboot cloud生命周期.md)
- 第512集 如何定位线上慢请求?