1、@PostConstruct是什么
@PostConstruct常用于bean生成后执行初始化操作。
2、@PostConstruct如何使用
package com.eden.research.api;
import com.eden.research.service.IDemoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
@RestController
@RequestMapping("/demo")
public class DemoApi {
@Resource
private IDemoService demoService;
@Value("${demo.config:a}")
private String config;
@GetMapping
public String demo() {
return demoService.demo();
}
@PostConstruct
private void init() {
System.out.println("执行初始化 PostConstruct 方法");
System.out.println("demoService = " + demoService);
System.out.println("config = " + config);
}
}
输出结果:
执行初始化 PostConstruct 方法
demoService = com.eden.research.service.impl.DemoService@386c295c
config = a
3、问题思考
- @PostConstruct 方法是否支持参数?
- 方法名有没要求?
- 访问修饰符有无要求?
- 执行顺序如何?
4、@PostConstruct原理
从启动到执行的调用栈
最终执行是通过反射执行的,执行的入参是null
另外,从注解说明中可以看到,该注解是用于依赖注入的bean。普通java对象使用该注解是无效的
5、总结
- @PostConstruct 是在bean生成后执行的,是通过反射的方式执行,只会执行一次。
- 被@PostConstruct注解的方法不能有参数。
- 从代码执行结果可以看出,相比静态初始化块,@PostConstruct注解的方法可以在自动注入完成后执行,可以借此机制在服务启动时实现对配置进行校验等功能