spring bean的生命周期面试回答及代码演示
前言:
在面试中经常会被问到谈谈你对spring bean生命周期的理解,如果单方面的在网站看写的博客很难理解的,最好自己写代码体会他的实现流程。
1.先了解这几个类的意思
BeanNameAware:设置bean的名称类
BeanFactoryAware:bean工厂类接口
ApplicationContextAware:上下文类
InitializingBean :初始加载bean对象类
DisposableBean:bean对象销毁类
开始代码演示
1.创建项目工程
2.pom.xml依赖引入
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.itheima</groupId><artifactId>spring_consumer</artifactId><version>1.0-SNAPSHOT</version><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-oxm</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>org.apache.xbean</groupId><artifactId>xbean-spring</artifactId><version>3.7</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency></dependencies>
</project>
3.applicationContext-user.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:amp="http://activemq.apache.org/schema/core"xmlns:context="http://www.springframework.org/schema/context"xmlns:jms="http://www.springframework.org/schema/jms"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd"><!-- spring bean生命周期执行流程 init-method="initMethod" :初始化方法destroy-method="destroyMethod":销毁bean对象方法--><bean id="userService" class="com.itheima.service.UserService" init-method="initMethod" destroy-method="destroyMethod"/><bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/><bean id="userSerivceImpl" class="com.itheima.service.impl.UserSerivceImpl"/></beans>
4.编写UserService服务类
package com.itheima.service;import java.util.Arrays;import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;public class UserService implements BeanNameAware,
BeanFactoryAware,ApplicationContextAware,InitializingBean,DisposableBean{// 对应<bean id="userService" />public void setBeanName(String name) {System.out.println("【步骤2】实现BeanNameAware接口,执行setBeanName方法,beanName值:userService");}public void setBeanFactory(BeanFactory beanFactory) throws BeansException {System.out.println("【步骤3】实现BeanFactoryAware接口,执行setBeanFactory()方法");}public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {String deanDefinitionNames = Arrays.toString(applicationContext.getBeanDefinitionNames());System.out.println("【步骤4】实现ApplicationContextAware接口,执行setApplicationContext方法 调用deanDefinitionNames="+deanDefinitionNames);}//通过注解@PostConstruct自定义初始化方法@PostConstructpublic void initPostConstruct(){System.out.println("【步骤6】通过注解@PostConstruct自定义initPostConstruct()【初始化方法1】");}public void afterPropertiesSet() throws Exception {System.out.println("【步骤7】实现InitializingBean初始化接口,执行afterPropertiesSe()方法执行【初始化方法2】");}//通过<bean>自定义init-method属性指定的初始化方法public void initMethod() throws Exception {System.out.println("【步骤8】执行spring配置文件bean标签的init-method属性【初始化方法2】");}//通过注解@PreDestroy自定义销毁方法@PreDestroypublic void preDestroy(){System.out.println("【步骤10】通过注解@PreDestroy自定义销毁方法preDestroy()【销毁方法1】");}//销毁bean对象public void destroy() throws Exception {System.out.println("【步骤11】实现DisposableBean接口的destroy()【销毁方法2】");}//通过<bean>自定义destroy-method属性指定的销毁方法public void destroyMethod() throws Exception {System.out.println("【步骤12】执行spring配置文件bean标签的destroy-method属性指定的【销毁方法3】");}}
5.编写UserServiceImpl实现类
package com.itheima.service.impl;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class UserSerivceImpl implements BeanPostProcessor{//Before前置初始化方法public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {System.out.println("【步骤5】实现类UserSerivceImpl实现BeanPostProcessor接口,执行postProcessBeforeInitialization()前置方法");return bean;}//After后置初始化方法public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {System.out.println("【步骤9】实现类UserSerivceImpl实现BeanPostProcessor接口,执行postProcessAfterInitialization()后置方法");return bean;}
}
6.编写测试类测试bean执行顺序
package com.itheima.service;import org.apache.xbean.spring.context.ClassPathXmlApplicationContext;public class TestBean {public static void main(String[] args) {/*** 当程序加载运行时会根据spring中配置文件找到bean配置的属性和方法,* 并通过java反射机制创建实例化bean对象;*/System.out.println("【步骤1】程序运行时,加载spring配置文件,实例化bean对象");ClassPathXmlApplicationContext contetx =new ClassPathXmlApplicationContext("applicationContext-user.xml");UserService user = contetx.getBean("userService",UserService.class);contetx.close();System.out.println("【步骤13】关闭spring bean容器contetx.close()");}
}
7.输出结果
【步骤1】程序运行时,加载spring配置文件,实例化bean对象
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
【步骤2】实现BeanNameAware接口,执行setBeanName方法,beanName值:userService
【步骤3】实现BeanFactoryAware接口,执行setBeanFactory()方法
【步骤4】实现ApplicationContextAware接口,执行setApplicationContext方法 调用deanDefinitionNames=[userService, org.springframework.context.annotation.CommonAnnotationBeanPostProcessor#0, userSerivceImpl]
【步骤5】实现类UserSerivceImpl实现BeanPostProcessor接口,执行postProcessBeforeInitialization()前置方法
【步骤6】通过注解@PostConstruct自定义initPostConstruct()【初始化方法1】
【步骤7】实现InitializingBean初始化接口,执行afterPropertiesSe()方法执行【初始化方法2】
【步骤8】执行spring配置文件bean标签的init-method属性【初始化方法2】
【步骤9】实现类UserSerivceImpl实现BeanPostProcessor接口,执行postProcessAfterInitialization()后置方法
【步骤10】通过注解@PreDestroy自定义销毁方法preDestroy()【销毁方法1】
【步骤11】实现DisposableBean接口的destroy()【销毁方法2】
【步骤12】执行spring配置文件bean标签的destroy-method属性指定的【销毁方法3】
【步骤13】关闭spring bean容器contetx.close()
8.在初始化阶段,有个特别重要的接口BeanPostProcessor,在初始化前、后调用
postProcessBeforeInitialization();//Before初始化前调用方法
postProcessAfterInitialization()//After初始化后调用方法
8.1实现流程图
9.初始化方式有三个,分别是
- InitializingBean类的afterPropertiesSet方法
- PostConstruct注解标注的方法
- spring配置文件applicationContext-user.xml的init-method="initMethod"
10.销毁方式有三个,分别是
- preDestroy注解标注的方法
- DisposableBean接口的destroy方法
- spring配置文件applicationContext-user.xml的配置的destroy-method=;"destroyMethod"
11.面试回答总结
1.根据程序加载运行输出结果回答:
【步骤1】程序运行时,加载spring配置文件,实例化bean对象
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
【步骤2】实现BeanNameAware接口,执行setBeanName方法,beanName值:userService
【步骤3】实现BeanFactoryAware接口,执行setBeanFactory()方法
【步骤4】实现ApplicationContextAware接口,执行setApplicationContext方法 调用deanDefinitionNames=[userService, org.springframework.context.annotation.CommonAnnotationBeanPostProcessor#0, userSerivceImpl]
【步骤5】实现类UserSerivceImpl实现BeanPostProcessor接口,执行postProcessBeforeInitialization()前置方法
【步骤6】通过注解@PostConstruct自定义initPostConstruct()【初始化方法1】
【步骤7】实现InitializingBean初始化接口,执行afterPropertiesSe()方法执行【初始化方法2】
【步骤8】执行spring配置文件bean标签的init-method属性【初始化方法2】
【步骤9】实现类UserSerivceImpl实现BeanPostProcessor接口,执行postProcessAfterInitialization()后置方法
【步骤10】通过注解@PreDestroy自定义销毁方法preDestroy()【销毁方法1】
【步骤11】实现DisposableBean接口的destroy()【销毁方法2】
【步骤12】执行spring配置文件bean标签的destroy-method属性指定的【销毁方法3】
【步骤13】关闭spring bean容器contetx.close()
面试回答:
1.当程序加载运行时会根据spring中配置文件找到bean配置的属性和方法,并通过java反射机制创建实例化bean对象。
Bean实现了BeanNameAware接口,执行了setBeanName方法,实现注入对象。
2.实现了BeanFactoryAware工厂接口,执行了setBeanFactory方法。
3.实现了ApplicationContext接口类,执行了setsetApplicationContest方法。
4.实现了BeanPostProcessor接口类,执行postProcessBeforeInitialization方法
5.实现了InitiliazingBean 执行afterPropertiesSet方法,并加载配置文件定义了init-method 则执行对应初始化方法BeanPostProcessor 执行postProcessorfterInitilization方法,完成 Bean的初始化,使得bean可以使用。
6.实现了DisposabileBean接口,加载配置文件中的destroy-method方法销毁bean对象实例。
简要回答:
- 程序加载时创建bean的实例化对象。
- 注入bean的相关实现接口管理bean对象。
- 初始化bean对象。
- 关闭并销毁bean实例化对象。
参考案例:https://blog.csdn.net/cool_summer_moon/article/details/106149339
写的有不足的地方欢迎同行评论提出观点,谢谢!!
spring bean的生命周期面试回答及代码演示相关推荐
- 字节跳动面试题:“请你描述下 Spring Bean 的生命周期?”
1. 引言 "请你描述下 Spring Bean 的生命周期?",这是面试官考察 Spring 的常用问题,可见是 Spring 中很重要的知识点. 我之前在准备面试时,去网上搜过 ...
- 带你读懂Spring Bean 的生命周期,嘿,就是玩儿~
带你读懂Spring Bean 的生命周期,嘿,就是玩儿~ 一.前言 今天我们来说一说 Spring Bean 的生命周期,小伙伴们应该在面试中经常遇到,这是正常现象.因为 Spring Bean 的 ...
- 再聊Spring Bean的生命周期
Spring Bean的生命周期是Spring面试热点问题.这个问题即考察对Spring的微观了解,又考察对Spring的宏观认识,想要答好并不容易!本文希望能够从源码角度入手,帮助面试者彻底搞定Sp ...
- 简述 Spring Bean的生命周期
"请你描述下 Spring Bean 的生命周期?",这是面试官考察 Spring 的常用问题,可见是 Spring 中很重要的知识点. 其实要记忆该过程,还是需要我们先去理解,本 ...
- Spring bean 实现生命周期的三种解决方案
Spring bean 实现生命周期的三种解决方案 参考文章: (1)Spring bean 实现生命周期的三种解决方案 (2)https://www.cnblogs.com/javawebsoa/a ...
- 请解释Spring Bean 的生命周期?
Spring Bean 的生命周期简单易懂.在一个bean 实例被初始化时,需要执行一系列的初始化操作以达到可用的状态.同样的,当一个bean 不在被调用时需要进行相关的析构操作,并从bean 容器中 ...
- Spring Bean的生命周期及接口回调
本篇介绍Spring框架为Spring Bean生命周期各阶段提供的回调接口,程序通过实现回调接口,可以在IOC容器实例化或销毁Bean的过程中,得到Bean的控制权,并对Bean进行预处理工作.通过 ...
- Spring Bean的生命周期(非常详细)
Spring作为当前Java最流行.最强大的轻量级框架,受到了程序员的热烈欢迎.准确的了解Spring Bean的生命周期是非常必要的.我们通常使用ApplicationContext作为Spring ...
- 【Spring Bean的生命周期】
Spring Bean的生命周期(非常详细) - Chandler Qian - 博客园
最新文章
- java项目中怎么查看用的序列_如何在Java应用程序中使用序列化分类器对...
- 【django】配置文件
- c语言如何用fscanf将字符串读取,在c语言中如何将文本内容 赋给一个 字符串
- [译] APT分析报告:04.Kraken - 新型无文件APT攻击利用Windows错误报告服务逃避检测
- WebRTC 及点对点网络通信机制
- fb静态区域_fb 静态数据
- java 模板模式_Java模板模式(Template模式)
- 支付系统设计:支付系统的账户模型(一)
- Java监听器Listener使用说明
- Java:中的String,StringBuilder,StringBuffer三者的区别
- 【Linux】15 张 Vim 速查表奉上,帮你提高 N 倍效率!
- 漂亮女生应聘华为的真实过程
- php小偷程序实例代码
- WPS正式推出了JS宏(WPS宏编辑器)如何切换会传统VB环境
- Java300StudyNote(7)-Java各版本JavaSE、JavaEE、JavaME
- 微信小程序云数据库的分页提取,解决提取大量数据的耗时问题
- 逆向app - 简单apk工具的安装
- 微信调试、手机QQ调试、Qzone之x5内核inspect调试解决方案
- python实时监控文件目录_教你三种方法,用 Python实时监控文件
- 运动学习与控制-学习笔记(三)——运动控制理论