最近重构公司项目,看到有用到该注解,就学习一下。
@PostContruct是spring框架的注解,在方法上加该注解会在项目启动的时候执行该方法,也可以理解为在spring容器初始化的时候执行该方法。
来看一下Spring官方文档对它的介绍:
The JSR-250 @PostConstruct and @PreDestroy annotations are generally considered best
practice for receiving lifecycle callbacks in a modern Spring application. Using these
annotations means that your beans are not coupled to Spring-specific interfaces. For details, see Using @PostConstruct and @PreDestroy.
If you do not want to use the JSR-250 annotations but you still want to remove
coupling, consider init-method and destroy-method bean definition metadata.
大概意思是,Servlet中增加了两个影响Servlet生命周期的注解,@PostConstruct和@PreDestroy,这两个注解被用来修饰一个非静态的void()方法。
写法有如下两种方式:
@PostConstruct
void Atest() {
System.out.println("Atest()");