@PostConstruct的使用

@PostConstruct

以Post为前缀的单词,指 在...之后。比如 postgraduate 就有大学毕业后的意思。

Construct 是构造方法。

@PostConstruct 是指在构造方法之后运行的意思。

执行顺序:

Constructor(构造方法) -> @PostConstruct注解的方法 -> 其他普通的方法

示例:

@Component
public class PostConstructDemo {

    @PostConstruct
    public void init() {
        System.out.println("init started");
    }

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

}

执行 doSomething() 方法后,可以看到 日志如下:

init started
doSomething.

@PostConstruct 的实际用途

可以用 @PostConstruct 进行初始化、赋值。然后在其他普通的方法里面使用。

比如:

@Component
public class PostConstructDemo2 {

    private static final Map<String, String> MAP = new HashMap<>();

    @PostConstruct
    public void init() {
        System.out.println("init started");
        MAP.put("key1", "value1");
        MAP.put("key2", "value2");

    }

    public void doSomething() {
        String value = MAP.get("key1");
        System.out.println("value:" + value);
    }

}

运行后,显示:

value结果为:value1

可见在 @PostConstruct 注解的方法中已经赋值成功,其他普通方法可以获取到值并使用了。

@PostConstruct 的不足

@PostConstruct 是在项目启动时,构造方法之后运行的,因此新增的配置项不会生效。
比如,在 @PostConstruct 修饰的方法中,查询数据表的配置,写入到Map中。
那么在启动服务之后,新增的配置项,PostConstruct无法获取,只能重启服务才能获取到最新的配置。

posted on 2023-06-16 00:01  乐之者v  阅读(218)  评论(0)    收藏  举报

导航