init-method,@postcontruct,afterPropertiesSet的先后顺序;[通俗易懂]

在牛客面经上遇到的一个面试题。突然想尝试下然后就开始做了测试ApplicationContextapplicationContext=newClassPathXmlApplicationContext("classpath:applicationContext.xml");TestDaotestDao=applicationContext.getBean(TestDao.class);((ClassPathXmlAp

大家好,又见面了,我是你们的朋友全栈君。

在牛客面经上遇到的一个面试题。突然想尝试下 然后就开始做了

测试

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        TestDao testDao = applicationContext.getBean(TestDao.class);
        ((ClassPathXmlApplicationContext) applicationContext).close();

测试的bean

@Component
public class TestDao  implements InitializingBean, DisposableBean {
    public TestDao() {
        System.out.println("constructor");
    }

    @Async
    public void query(){
        System.out.println("Hello Spring!");
    }

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

    public void InitMethod(){
        System.out.println("InitMethod");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("destroy");
    }
    @PreDestroy
    public void PreDestroy(){
        System.out.println("PreDestroy");
    }
    public void destroyMethod(){
        System.out.println("destroyMethod");
    }
}

xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd

        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>
    <bean id="testDao" class="com.test.dao.TestDao" init-method="InitMethod" destroy-method="destroyMethod"></bean>

</beans>

执行之后打印的结果 file 总的来说就是打印的结果是构造方法->注解@PostConstruct方法->InitializingBean接口的afterPropertiesSet方法->xml中配置的init-method方法 同理销毁也是一样注解@PreDestroy方法->DisposableBean接口的destroy方法->xml中配置的destroy-method方法

源码

通过断点调试发现几个初始化方法都定位到了AbstractAutowireCapableBeanFactory的initializeBean方法中

protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                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;
    }

后面执行的两个方法 protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd) throws Throwable {

    boolean isInitializingBean = (bean instanceof InitializingBean);
    if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
        if (logger.isTraceEnabled()) {
            logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
        }
        if (System.getSecurityManager() != null) {
            try {
                AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
                    ((InitializingBean) bean).afterPropertiesSet();
                    return null;
                }, getAccessControlContext());
            }
            catch (PrivilegedActionException pae) {
                throw pae.getException();
            }
        }
        else {
        //执行afterPropertiesSet方法
            ((InitializingBean) bean).afterPropertiesSet();
        }
    }

    if (mbd != null && bean.getClass() != NullBean.class) {
        String initMethodName = mbd.getInitMethodName();
        if (StringUtils.hasLength(initMethodName) &&
                !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                !mbd.isExternallyManagedInitMethod(initMethodName)) {
                //执行的是xml中自定义的init-method方法
            invokeCustomInitMethod(beanName, bean, mbd);
        }
    }
}

欢迎搜索关注本人的公众号【微瞰技术】,以及总结的分类面试题https://github.com/zhendiao/JavaInterview

file

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/127461.html原文链接:https://javaforall.net

(0)
上一篇 2022年4月9日 下午8:40
下一篇 2022年4月9日 下午9:00


相关推荐

  • pytest fixtures_pytest命令

    pytest fixtures_pytest命令fixture的优势Pytest的fixture相对于传统的xUnit的setup/teardown函数做了显著的改进:命名方式灵活,不局限于setup和teardown这几个命名conf

    2022年7月31日
    5
  • 怎样设置CCProxy

    怎样设置CCProxy怎样设置 CCProxy 代理服务器 CCProxy 能够实现局域网内共享上网和帐号控制 界面友好 设置简单 功能强大 支持 Modem ADSL 宽带等共享上网 支持网页缓存 能实现多人共享浏览网页 收发邮件和联络 同时还能监视上网记录 可以针对不同用户合理的安排上网时间和带宽流量控制 有效地进行网站过滤 是非常适合政府部门 公司和学校使用的代理服务器软件 它能帮您搭建

    2025年10月8日
    7
  • 计算机应用模块数量如何填写,职称计算机考试科目、模块数量介绍

    计算机应用模块数量如何填写,职称计算机考试科目、模块数量介绍原标题:职称计算机考试科目、模块数量介绍全国计算机应用能力考试坚持”实事求是,区别对待,逐步提高”的原则,不同地区、不同部门根据本地区、本部门的实际情况,确定适合本地区、本部门的考试范围要求。1、不同地区和部门自主确定应考科目数量在对专业技术人员计算机应用能力的具体要求上,各省、自治区、直辖市人事厅(局)和国务院有关部门干部(人事)部门应结合本地区、本部门的实际情况,确定本地区、本部门在评聘专业技…

    2022年5月5日
    113
  • nonce与时间戳

    nonce与时间戳nonce 是为了防止重放攻击产生的 nonce 是服务器产生的随机数 当客户端第一次发出请求时 获取 nonce 将其与原文一起进行加密 进行发送 服务器使用同样的算法进行加密 与客户端发送过来的密文进行对比 若用户名一样则证明消息的有效性 若发现该 nonce 在数据库中已经存在 则该请求可能为恶意请求 但是由于 nonce 是随机产生的 所以可能会存在重复 针对此情况 出现了时间戳 时间戳是服务器

    2026年3月19日
    3
  • python 图片重命名_python文件改名

    python 图片重命名_python文件改名由于两个文件夹下的图片名字是一样的,但是我想让另一个文件夹接在一个文件夹之后重新命名,也就是从732.jpg开始递增命名。想到以后可能还会经常遇到这种情况,所以还是保存一下,以后就懒得再重新写了。”’图像批量重命名”’importosstart=732#开始的序号image_dir=’./output/’#源图片路径images_list=os.listdir(image_dir)nums=len(os.listdir(image_dir))print

    2025年9月15日
    5
  • java字符串拼接的几种方式

    java字符串拼接的几种方式1 plus 方式当左右两个量其中有一个为 String 类型时 用 plus 方式可将两个量转成字符串并拼接 Stringa intb 0xb Stringc a b 2 concat 方式当两个量都为 String 类型且值不为 null 时 可以用 concat 方式 Stringa a Stringb b Stringc a concat b 理论上 此时拼接效率应该最高

    2026年3月17日
    1

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号