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注释规则

  1. 除了 * 这个特殊情况以外,其他情况都不允许有参数,否则spring框架会报IllegalStateException;而且返回值要是void,但实际也可以有返回值,至少不会报错,只会忽略

  2. 方法随便你用什么权限来修饰,public、protected、private都可以,反正功能是由反射来实现

  3. 方法不可以是static的,但可以是final的

所以,综上所述,在spring项目中,在一个bean的初始化过程中,方法执行先后顺序为

Constructor > @Autowired > @PostConstruct

先执行完构造方法,再注入依赖,最后执行初始化操作,所以这个注解就避免了一些需要在构造方法里使用依赖组件的尴尬。

来源:https://blog.csdn.net/m0_53288098/article/details/122355201

标签:@postconstruct,注解,spring
0
投稿

猜你喜欢

  • 详解Java中的线程池

    2023-11-10 16:33:27
  • MyBatis超详细讲解如何实现分页功能

    2023-08-22 23:06:51
  • SpringBoot中@ConfigurationProperties注解实现配置绑定的三种方法

    2023-03-19 12:36:25
  • 简单了解springboot的jar包部署步骤

    2021-07-02 14:22:48
  • IDEA实现添加 前进后退 到工具栏的操作

    2021-08-30 21:34:48
  • java读写二进制文件的解决方法

    2022-08-03 14:45:55
  • Java实战之在线租房系统的实现

    2022-09-29 04:44:18
  • Android下拉列表spinner的实例代码

    2023-07-31 20:39:47
  • Android超清晰6.0权限申请AndPermission

    2023-08-05 10:52:26
  • Springmvc发送json数据转Java对象接收

    2023-07-07 16:26:16
  • Java中的interrupted()和isInterrupted()

    2023-06-17 22:16:31
  • 详解Flutter网络图片本地缓存的实现

    2023-08-18 19:44:43
  • springMVC自定义注解,用AOP来实现日志记录的方法

    2023-11-29 13:58:53
  • 浅谈mybatis中SQL语句给boolean类型赋值问题

    2023-01-19 15:15:42
  • Mybatis-Plus的使用详解

    2022-01-18 18:39:27
  • IDEA解决springboot热部署失效问题(推荐)

    2023-08-12 10:40:49
  • 解析Android 8.1平台SystemUI 导航栏加载流程

    2023-06-23 15:21:21
  • Java实现登录与注册页面

    2023-04-17 03:21:20
  • Spring boot jpa 删除数据和事务管理的问题实例详解

    2022-07-02 12:11:43
  • MyBatis Plus 入门使用详细教程

    2023-08-23 05:48:33
  • asp之家 软件编程 m.aspxhome.com