@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   乐之者v  阅读(185)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2016-06-16 Android笔记:RelativeLayout
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示