最近重构公司项目,看到有用到该注解,就学习一下。
@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()");
}
//或者
@PreDestroy
void Btest() {
System.out.println("Btest()");
}
另外,spring中Constructor、@Autowired、@PostConstruct的顺序
Constructor >> @Autowired >> @PostConstruct
JSR是什么?
JSR是Java Specification Requests的缩写,意思是Java 规范提案。是指向JCP(Java Community Process)提出新增一个标准化技术规范的正式请求。任何人都可以提交JSR,以向Java平台增添新的API和服务。JSR已成为Java界的一个重要标准。(来自百度百科)
下面在SpringBoot中创建两个被@Component注解的类,来看一下@PostConstruct、@Autowired和Constructor的关系。
创建类A
@Component
public class A {
@Autowired
private B b;
public A() {
System.out.println("A() - 默认构造");
}
@PostConstruct
void Atest() {
System.out.println("Atest()");
}
}
创建类B
@Component
public class B {
public B() {
System.out.println("B() - 默认构造");
}
@PostConstruct
void Btest() {
System.out.println("Btest()");
}
}
创建完成之后,运行SpringBoot程序,查看控制台输出即可,输出结果如下所示: