有时我们想在SpringBoot启动时调用某个方法,从数据库中获取一些数据作为缓存,这时只需要使用@PostConstruct就可以。
不多说,直接上代码。
@Component
public class EduCache {
@Autowired
TeacherPOMapper teacherPOMapper;
public static Map<String, String> gradeMap = new HashMap<>();
@PostConstruct
public void init(){
// 从数据库中查询数据
List<Course> courseTypeVOS = teacherPOMapper.selectCourseType();
// ....编写自己的业务处理
}
}
}
@PostConstruct
被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。
如果想在生成对象时完成某些初始化操作,而偏偏这些初始化操作又依赖于依赖注入,那么就无法在构造函数中实现就需要使用@PostConstruct注解一个方法来完成初始化,@PostConstruct注解的方法将会在依赖注入完成后被自动调用。