@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 注解的方法中已经赋值成功,其他普通方法可以获取到值并使用了。