【@PostConstruct、 @Autowired与构造函数的执行顺序】


最近对同事代码进行codeReview时候发现用@PostConstruct注解,特地对此注解执行顺序进行了研究,整理记录如下。

一、@PostConstruct介绍

Java提供的注解,被用来修饰方法,被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。

(1)结论:

调用的顺序为: 构造函数 > @Autowired > @PostConstruct

(2)作用:

@PostConstruct注解的方法在项目启动的时候执行这个方法,也可以理解为在spring容器启动的时候执行,可作为一些数据的常规化加载,比如读取数据字典之类、目录树缓存

二、Spring框架中在bean初始化和销毁时候执行实现方式

Spring框架中在bean初始化和销毁时候执行某个方法的三种实现方式。
(1)Spring框架中通过注解@PostConastruct 和 @PreDestroy来实现Bean初始化执行和销毁时候执行方法;

(2)Spring框架中通过实现接口InitializingBean ,DisposableBean来实现Bean初始化执行和销毁时候执行方法;

(3)Spring框架中通过xml配置文件中bean的init-method=“” destroy-method=""来实现Bean初始化执行和销毁时候执行方法;

Spring Bean执行顺序
在这里插入图片描述

三、项目验证

1.MyServiceImpl

package com.huahua.myIdea.service.serviceImpl;

import com.huahua.myIdea.service.MyService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;

@Service
public class MyServiceImpl implements MyService, InitializingBean {

    @Override
    public int addTotal(int x, int y) {
        return 0;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("开始执行 afterPropertiesSet 方法: MyServiceImpl");
    }

    @PostConstruct
    public void postConstructMethod() {
        System.out.println("开始执行 PostConstruct 方法: MyServiceImpl");
    }

    @Autowired
    private void testAutowired(){
        System.out.println("开始执行 testAutowired 方法: MyServiceImpl");
    }

    MyServiceImpl(){
        System.out.println("开始执行 构造函数MyServiceImpl : MyServiceImpl");
    }
}

2.测试结果

在这里插入图片描述

3. 项目源码

项目结构及代码下载,欢迎star~~
MyIdea
在这里插入图片描述
参考资料
InitializingBean、BeanPostProcessor、init-method、@PostConstruct执行先后顺序
SpringBoot 学习之 @PostConstruct、 @Autowired与构造函数的执行顺序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
@PostConstruct构造函数都是在Servlet加载时调用的方法,但它们之间有一些区别。 首先,构造函数是在对象创建时调用的,用于初始化对象的状态。构造函数定义了对象的属性和行为,并可以接受参数。构造函数在对象创建时被调用,因此它是首先被执行的。 而@PostConstruct注解是一种在对象创建后,依赖注入完成后执行的方法。它被用来标记一个方法,在对象的所有依赖关系都被注入后,执行一些初始化操作。@PostConstruct方法在构造函数执行后被调用,因此它是构造函数执行完毕后被执行的。 当@PostConstruct、@Autowired构造函数在同一个类中时,它们的执行顺序是:构造函数 -> @Autowired -> @PostConstruct。也就是说,首先执行构造函数,然后进行依赖注入,最后执行@PostConstruct注解标记的方法[2]。 当@PostConstruct、@Autowired构造函数在不同的类中时,它们的执行顺序是:构造函数 -> @Autowired -> @PostConstruct。同样地,首先执行构造函数,然后进行依赖注入,最后执行@PostConstruct注解标记的方法。此时,@PostConstruct注解只会在第一次创建实例时被调用,之后的实例创建过程中将不再执行。 总结起来,构造函数用于对象的初始化,而@PostConstruct注解用于对象依赖注入完成后的初始化操作。它们在执行顺序和作用上有所区别。 引用 引用 引用[3

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值