@PostConstruct注解介绍
今天在写一个基于SpringBoot的论坛开源项目时,遇到一个比较陌生的注解:@PostConstruct
使用场景
/**
* @Auther: csp1999
* @Date: 2020/11/25/10:56
* @Description: xxxx
*/
@Component
public class XXXXX {
...
@PostConstruct
public void init() {
...
}
}
因为该类被注入到了Spring容器中,起初我以为该注解是由 Spring 官方提供的,而查了一些文章后才知道是Java自己的注解,位于javax 包下。
注解作用
@PostConstruct该注解是用来修饰一个非静态的void()方法,其修饰的方法在构造函数执行之后执行。
比如,在Spring框架中,如果某个方法需要使用@PostConstruct注解修饰的话,那么加上此注解的该方法在整个Bean 初始中的执行顺序为:
Constructor(构造方法) —>@Autowired(依赖注入) —>@PostConstruct(注释的方法)
Demo案例
TestService.java
/**
* @Auther: csp1999
* @Date: 2020/11/25/12:13
* @Description:
*/
@Component
public class TestService {
public TestService(){
System.out.println("TestService注入到了IO容器...");
}
}
MyTest.java
/**
* @Auther: csp1999
* @Date: 2020/11/25/12:11
* @Description:
*/
@Component
public class MyTest {
@Autowired
private TestService testService;
public MyTest(){
System.out.println("MyTest构造函数执行...");
}
@PostConstruct
public void init(){
System.out.println("@PostConstruct注解修饰的方法执行...");;
}
}
测试调用
@SpringBootTest
class ApplicationTest {
@Autowired
MyTest myTest;
@Test
void test03() {
System.out.println(myTest);
}
}
输出结果
结论
在Spring框架中,如果某个方法需要使用@PostConstruct注解修饰的话,那么加上此注解的该方法在整个Bean 初始中的执行顺序为:
Constructor(构造方法) —>@Autowired(依赖注入) —>@PostConstruct(注释的方法)