> 文档中心 > 白话@PostConstruct

白话@PostConstruct

白话@PostConstruct

    • @PostConstruct是什么:
    • 案例:
    • 运用场景:

面试的时候遇到过一个问题,Spring中,怎么让A对象在初始化的时候调用到B对象的方法

拿到这个问题的时候我一脸懵逼的,这是什么问题,还会有这样的使用场景嘛?

当时最先想到的是在A对象的构造方法里手动new一个B对象,然后调用其方法。
但当前是在Spring环境中,我们是通过@Autowired自动注入来取到目标对象的,所以不能用手动的new方法来做。

这时候就会想:
好,我不new ,我@Autowired一个B对象,然后在A对象的构造方法里调用总可以吧。
抱歉,也不行,为什么呢?

要将对象B注入到对象A,那么首先就必须得生成对象B和对象A,才能执行注入。所以,如果一个类A中有个成员变量B被@Autowried注解,那么@Autowired注入是发生在A的构造方法执行完之后的。

@PostConstruct是什么:

@PostConstruct是JDK提供的注解,打在方法上,被@PostConstruct修饰的方法会在服务器加载Bean的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行。白话@PostConstruct

案例:

现在我们有两个类,一个ServerA,一个ServerB。

ServerA注入了ServerB,在@PostConstruct修饰的方法init()中调用了ServerB的方法。并且拿到返回值,复制给SeverA自己的一个属性name,紧接着system.out打印出name的值。

@Componentpublic class ServerA {    @Autowired    ServerB serverB;    private String name;    @PostConstruct    public void init(){ String userName = serverB.getNameById(1); this.name = userName; System.out.println(name);    }}

ServerB只有一个普通方法,返回一个String对象。

@Componentpublic class ServerB {    public String getNameById(int id){ //模拟查数据库,根据id查出姓名 return "张三";    }}

现在启动整个SpringBoot项目。可以看到控制台打印出了”张三“。

白话@PostConstruct

运用场景:

项目启动时候的初始化赋值操作,离不开@PostConstruct注解。

如果想在生成对象时完成某些初始化操作,而偏偏这些初始化操作又依赖于依赖注入,那么就无法在构造函数中实现。为此,可以使用@PostConstruct注解一个方法来完成初始化,@PostConstruct注解的方法将会在依赖注入完成后被自动调用。