最佳实践--Spring容器初始化完成之后执行某个方法

来源:互联网 发布:solr数据没有了 编辑:程序博客网 时间:2024/06/05 03:54

在做javaweb项目的时候,当用户访问的时候需要从数据库加载数据,现在要在容器初始化完成之后直接把数据放入缓存,当用户访问的时候提高速度。

查阅相关spring文档,找到了一个最佳实践(best practice)

The JSR-250 @PostConstruct and @PreDestroy annotations are generally considered best practice for receiving lifecycle callbacks in a modern Spring application. Using these annotations means that your beans are not coupled to Spring specific interfaces. For details see Section 6.9.8, “@PostConstruct and @PreDestroy”. 
If you don’t want to use the JSR-250 annotations but you are still looking to remove coupling consider the use of init-method and destroy-method object definition metadata.

详情看参考文献

直接上代码

import javax.annotation.PostConstruct;import org.springframework.stereotype.Component;@Componentpublic class InitData {    @PostConstruct    public void init() {        System.out.println("初始化数据方法");    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

这里写图片描述


0 0
原创粉丝点击