Java面试题:@PostConstruct、init-method和afterPropertiesSet执行顺序?
在Spring框架中,@PostConstruct注解、init-method属性、以及afterPropertiesSet()方法通常用于初始化Bean的逻辑。它们都提供了在Bean创建和初始化完成后执行的方法,但执行顺序有所不同。
想要知道@PostConstruct、init-method、afterPropertiesSet()的执行顺序,只要搞明白它们各自在什么时候被谁调用就行了。
代码如下:
import org.springframework.beans.factory.InitializingBean;
import javax.annotation.PostConstruct; public class Foo implements InitializingBean { public void init(){
System.out.println("执行了init生命周期的初始化回调");
} @PostConstruct
public void postConstruct(){
System.out.println("执行了postConstruct生命周期的初始化回调");
} @Override
public void afterPropertiesSet() {
System.out.println("执行了afterPropertiesSet生命周期的初始化回调");
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class InitConfiguration {
@Bean(initMethod = "init")
public Foo getInitMethodBean() {
return new Foo();
}
}
执行启动类,可以看到在控制台中输出:
执行了postConstruct生命周期的初始化回调
执行了afterPropertiesSet生命周期的初始化回调
执行了init生命周期的初始化回调
@PostConstruct是Java EE 5引入的一个注解,它用于标记一个方法,该方法会在依赖注入完成后自动执行。这意味着,一旦Spring容器完成了Bean的实例化和属性赋值,就会调用这个方法。通常,我们会在这个方法中做一些初始化工作,比如启动服务、初始化数据库连接等。
init-method属性是Spring Bean的一个属性,它允许我们指定一个初始化方法。这个方法会在Bean实例化并完成属性注入后自动执行。与@PostConstruct注解不同的是,init-method属性并不依赖于Spring容器,因此可以在没有Spring的环境中运行。
afterPropertiesSet是SpringFramework中的一个初始化方法,它属于 InitializingBean接口的一部分。当bean的所有属性被Spring容器设置之后,这个方法会被自动调用。它允许开发者在bean属性设置完成之后执行一些特定的操作,如数据库连接池的初始化等。这个方法是在执行其他初始化方法之前被调用的。
源码分析:
通过断点调试发现几个初始化方法都定位到AbstractAutowireCapableBeanFactory的initializeBean方法中
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
invokeAwareMethods(beanName, bean);
return null;
}
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 此处执行的是@PostConstruct注解的方法 InitDestroyAnnotationBeanPostProcessor#postProcessBeforeInitialization
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 执行的是afterPropertiesSet和init-method方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
执行afterPropertiesSet和init-method方法,在invokeInitMethods方法里面,如下:
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable { boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
((InitializingBean) bean).afterPropertiesSet();
return null;
}
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
// 执行afterPropertiesSet方法
((InitializingBean) bean).afterPropertiesSet();
}
} if (mbd != null) {
String initMethodName = mbd.getInitMethodName();
if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
// 执行自定义的init-method方法
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
最终的结论是:@PostConstruct > afterPropertiesSet() > initMethod()的顺序
往期面试题:
Java面试题:SimpleDateFormat是线程安全的吗?使用时应该注意什么?
Java面试题:细数ThreadLocal大坑,内存泄露本可避免
Java面试题:为什么HashMap不建议使用对象作为Key?
Java面试题:你知道Spring的IOC吗?那么,它为什么这么重要呢?
Java面试题:@PostConstruct、init-method和afterPropertiesSet执行顺序?的更多相关文章
- 浅谈Java语言中try{}catch{}和finally{}的执行顺序问题
浅谈Java语言中try{}catch{}和finally{}的执行顺序问题 2019-04-06 PM 13:41:46 1. 不管有没有出现异常,finally块中代码都会执行: 2. 当t ...
- java基本数据类型,访问控制符,运算符执行顺序
1.java数据类型 内置数据类型:boolean(1), byte(8), char(16), short(8), int(32), long(64), float(32), double(64) ...
- java中的try-catch-finally中的return的执行顺序
在这里看到了try catch finally块中含有return语句时程序执行的几种情况,但其实总结的并不全,而且分析的比较含糊.但有一点是可以肯定的,finally块中的内容会先于try中的ret ...
- Java中if else条件判断语句的执行顺序
学习目标: 掌握 if else 条件判断的使用 学习内容: 1.if语法 if(boolean表达式) { 语句体; } if后面的{}表示一个整体-代码块,称之为语句体,当boolean表达式为t ...
- JAVA代码中加了Try...Catch的执行顺序
public static String getString(){ try { //return "a" + 1/0; return "a"; } catch ...
- Java静态代码块、构造代码块执行顺序问题
package com.zxl.staticdemo; public class BlockTest { static { System.out.println("BlockTest静态代码 ...
- Python面试题之多个装饰器执行顺序
疑问 大部分涉及多个装饰器装饰的函数调用顺序时都会说明它们是自上而下的,比如下面这个例子: def decorator_a(func): print 'Get in decorator_a' def ...
- java中异常处理finally和return语句的执行顺序
finally代码块的语句在return之前一定会得到执行 如果try块中有return语句,finally代码块没有return语句,那么try块中的return语句在返回之前会先将要返回的值保存, ...
- java有参无参构造器的的执行顺序
这里拿了用数组构造栈的一段代码说明一下 public class StackArray<E> { private Object[] data = null; private int max ...
- java静态代码块,构造方法,初始化块的执行顺序
代码Parent和Sub进行讲解 public class Parent { private static final String name; public Parent() { System.ou ...
随机推荐
- Apache服务器打开网页是乱码解决方案
当 Apache 服务器显示乱码时,可以使用两种方法解决: 1. 服务器端 可以在 Apache 的配置文件中添加以下内容来设置默认编码为UTF-8: AddDefaultCharset utf-8 ...
- postman测试接口时的参数对应接口的两种情况
第一种通过json字符串的情况去进行测试,最终将json字符串转成对应的对象 代码里面一定要加上@RequestBody注解,即使是一个字符串也需要加这个注解 第二种通过key-value的形式去加入 ...
- OpenHarmony社区运营报告(2022年9月)
篇首语 在开放原子开源基金会.OpenAtom OpenHarmony(简称"OpenHarmony")工作委员会.会员及共建单位和开发者的共同努力下,OpenHarmony在技术 ...
- Go 语言中的 Switch 语句详解
switch语句 使用switch语句来选择要执行的多个代码块中的一个. 在Go中的switch语句类似于C.C++.Java.JavaScript和PHP中的switch语句.不同之处在于它只执行匹 ...
- std::thread 三:条件变量(condition_variable())
condition_variable . wait . notify_one . notify_all *:notify_one:通知(唤醒)一个线程 *:notify_all:通知( ...
- IDEA 各个版本下载指引
1.IDEA 其它版本下载指引 网址: https://www.jetbrains.com.cn/idea/download/other.html 2.下载问题 下载哪个版本? win + R 打开命 ...
- 详解K8s 镜像缓存管理kube-fledged
本文分享自华为云社区<K8s 镜像缓存管理 kube-fledged 认知>,作者: 山河已无恙. 我们知道 k8s 上的容器调度需要在调度的节点行拉取当前容器的镜像,在一些特殊场景中, ...
- nginx重新整理——————nginx 模块[十]
前言 简单介绍一下nginx的模块. 正文 https://nginx.org/en/docs/ 这里面可以看到官方模块. 比如打开这个模块: https://nginx.org/en/docs/ht ...
- JavaScript中的事件模型如何理解?
一.事件与事件流 javascript中的事件,可以理解就是在HTML文档或者浏览器中发生的一种交互操作,使得网页具备互动性, 常见的有加载事件.鼠标事件.自定义事件等 由于DOM是一个树结构,如果在 ...
- 力扣1069(MySQL)-产品分析Ⅱ(简单)
题目: 编写一个 SQL 查询,按产品 id product_id 来统计每个产品的销售总量. 查询结果格式如下面例子所示: 解题思路: 没有用到product表,直接在sales表中使用聚合函数: ...