Spring框架中@PostConstruct注解详解
作者:大局观的小老虎 时间:2021-09-20 09:35:58
初始化方式一:@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();
}
补充:@PostConstruct注释规则
除了 * 这个特殊情况以外,其他情况都不允许有参数,否则spring框架会报IllegalStateException;而且返回值要是void,但实际也可以有返回值,至少不会报错,只会忽略
方法随便你用什么权限来修饰,public、protected、private都可以,反正功能是由反射来实现
方法不可以是static的,但可以是final的
所以,综上所述,在spring项目中,在一个bean的初始化过程中,方法执行先后顺序为
Constructor > @Autowired > @PostConstruct
先执行完构造方法,再注入依赖,最后执行初始化操作,所以这个注解就避免了一些需要在构造方法里使用依赖组件的尴尬。
来源:https://blog.csdn.net/m0_53288098/article/details/122355201
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解Java中的线程池
![](https://img.aspxhome.com/file/2023/9/59369_0s.png)
MyBatis超详细讲解如何实现分页功能
![](https://img.aspxhome.com/file/2023/6/58216_0s.png)
SpringBoot中@ConfigurationProperties注解实现配置绑定的三种方法
![](https://img.aspxhome.com/file/2023/9/60319_0s.png)
简单了解springboot的jar包部署步骤
IDEA实现添加 前进后退 到工具栏的操作
![](https://img.aspxhome.com/file/2023/7/62687_0s.jpg)
java读写二进制文件的解决方法
Java实战之在线租房系统的实现
![](https://img.aspxhome.com/file/2023/8/60808_0s.jpg)
Android下拉列表spinner的实例代码
![](https://img.aspxhome.com/file/2023/2/86012_0s.jpg)
Android超清晰6.0权限申请AndPermission
Springmvc发送json数据转Java对象接收
Java中的interrupted()和isInterrupted()
![](https://img.aspxhome.com/file/2023/6/57596_0s.png)
详解Flutter网络图片本地缓存的实现
springMVC自定义注解,用AOP来实现日志记录的方法
浅谈mybatis中SQL语句给boolean类型赋值问题
Mybatis-Plus的使用详解
![](https://img.aspxhome.com/file/2023/1/61801_0s.jpg)
IDEA解决springboot热部署失效问题(推荐)
![](https://img.aspxhome.com/file/2023/8/58148_0s.png)
解析Android 8.1平台SystemUI 导航栏加载流程
Java实现登录与注册页面
![](https://img.aspxhome.com/file/2023/1/61001_0s.jpg)
Spring boot jpa 删除数据和事务管理的问题实例详解
MyBatis Plus 入门使用详细教程
![](https://img.aspxhome.com/file/2023/3/58153_0s.png)