博客
关于我
@PostConstruct、@PreDestroy注解总结
阅读量:405 次
发布时间:2019-03-05

本文共 1351 字,大约阅读时间需要 4 分钟。

Spring中的@PostConstruct和@PreDestroy注解

1. 应用场景

在Spring框架中,@PostConstruct注解用于在依赖注入完成后执行一次初始化操作。这非常有用当需要在对象构造完成后进行一些依赖的查询或操作时。例如,可以在构造一个对象后,从数据字典获取配置信息进行初始化操作。@PostConstruct注解只能用于初始化操作,且只会在依赖注入完成后执行一次。

而@PreDestroy注解则用于在对象销毁前释放资源。常见的场景包括关闭数据库连接、释放文件资源或清理内存等。

2. 加载顺序

Spring中的加载顺序遵循以下规则:

  • 首先是构造函数(Constructor)
  • 其次是依赖注入(@Autowired)
  • 最后是@PostConstruct初始化方法

在服务器环境中,加载顺序扩展到更大的范围,包括:

  • 服务器加载Servlet
  • servlet构造函数加载
  • @PostConstruct初始化
  • Service初始化(init方法)
  • Service销毁(destroy)
  • @PreDestroy注解处理
  • 服务器卸载Servlet

3. 代码示例

以下是一个使用@PostConstruct注解的典型示例:

@Component public class DbInit { @Autowired private UserRepository userRepository;
@PostConstruct  private void postConstruct() {      User admin = new User("admin", "admin password");      User normalUser = new User("user", "user password");      userRepository.save(admin, normalUser);  }

}

以下是一个使用@PreDestroy注解的示例:

@Component public class UserRepository { private DbConnection dbConnection;
@PreDestroy  public void preDestroy() {      dbConnection.close();  }

}

4. Java 9及以上版本的注意事项

需要注意的是,@PostConstruct和@PreDestroy注解原本属于Java EE的一部分,但在Java 9中被标记为deprecated,并在Java 11被正式移除。因此,在Java 11及以上版本中,如果仍想使用这些注解,需要手动添加相应的依赖:

javax.annotation
javax.annotation-api
1.3.2

这样可以确保在最新版本的Java中仍然能够正常使用这些注解。

总结

@PostConstruct和@PreDestroy注解在Spring框架中提供了强大的初始化和销毁操作能力。理解它们的应用场景和加载顺序,对于优化Spring应用程序的资源管理至关重要。此外,随着Java版本的更新,正确处理这些注解的依赖也是开发者需要注意的事项。

转载地址:http://zphwz.baihongyu.com/

你可能感兴趣的文章
npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
查看>>
npm安装教程
查看>>
npm报错Cannot find module ‘webpack‘ Require stack
查看>>
npm报错Failed at the node-sass@4.14.1 postinstall script
查看>>
npm报错fatal: Could not read from remote repository
查看>>
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错TypeError: this.getOptions is not a function
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用操作---npm工作笔记003
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm设置镜像如淘宝:http://npm.taobao.org/
查看>>
npm配置安装最新淘宝镜像,旧镜像会errror
查看>>