在做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;
@Component
public class InitData {
    @PostConstruct
    public void init() {
        System.out.println("初始化数据方法");
    }
}

这里写图片描述

参考文献

Spring官方文档

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐