当前位置:网站首页>@PostConstruct注解详解
@PostConstruct注解详解
2022-08-02 07:29:00 【sebeefe】
初始化方式一:@PostConstruct注解
假设类UserController有个成员变量UserService被**@Autowired**修饰,那么UserService的注入是在UserController的构造方法之后执行的。
如果想在UserController对象生成时候完成某些初始化操作,而偏偏这些初始化操作又依赖于依赖注入的对象,那么就无法在构造函数中实现(ps:spring启动时初始化异常),例如:
public class UserController {
@Autowired
private UserService userService;
public UserController() {
// 调用userService的自定义初始化方法,此时userService为null,报错
userService.userServiceInit();
}
}
因此,可以使用@PostConstruct注解来完成初始化,@PostConstruct注解的方法将会在UserService注入完成后被自动调用。
public class UserController {
@Autowired
private UserService userService;
public UserController() {
}
// 初始化方法
@PostConstruct
public void init(){
userService.userServiceInit();
}
}
**总结:**类初始化调用顺序:
(1)构造方法Constructor
(2)@Autowired
(3)@PostConstruct
初始化方式二:实现InitializingBean接口
除了采用注解完成初始化,也可以通过实现InitializingBean完成类的初始化
public class UserController implements InitializingBean {
@Autowired
private UserService userService;
public UserController() {
}
// 初始化方法
@Override
public void afterPropertiesSet() throws Exception {
userService.userServiceInit();
}
}
比较常见的如SqlSessionFactoryBean,它就是通过实现InitializingBean完成初始化的。
@Override
public void afterPropertiesSet() throws Exception {
// buildSqlSessionFactory()是完成初始化的核心方法,必须在构造方法调用后执行
this.sqlSessionFactory = buildSqlSessionFactory();
}
先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦
边栏推荐
猜你喜欢

OSPF 综合实验

WebRTC系列-SDP之编码信息收集

DeadLock的可视化分析

MySQL优化:从十几秒优化到三百毫秒

MySQL-索引详解

Splunk Field Caculated Calculated Field

MySQL - index explanation

spark architecture

Aided by training and learning by battle | The new version of the Offensive and Defense World Platform is officially launched!

A full review of mainstream timed task solutions
随机推荐
Inverter Phase Locking Principle and DSP Implementation
flutter在导航栏处实现对两个列表的点击事件
MySQL优化之慢日志查询
Probability Theory and Mathematical Statistics
MySQL-索引优化和查询优化
MGRE综合实验
【Network】IP, subnet mask
Introduction to mysql operation (4) ----- data sorting (ascending, descending, multi-field sorting)
MySQL优化:从十几秒优化到三百毫秒
Neural network
Splunk Field Caculated Calculated Field
playwright 爬虫使用
Inverter insulation detection detection function and software implementation
WebRTC系列-SDP之编码信息收集
MySQL-FlinkCDC-Hudi enters the lake in real time
HCIP 第十二天
研发过程中的文档管理与工具
Enterprise training and reproduction guidebook - training and reasoning of the OpenPose model based on Huawei ModelArts platform, realizing the recognition of two behaviors of climbing and climbing ov
Metasploit (MSF) Basic Super Detailed Edition
MySQL-基础