使用 Spring MVC 在应用程序启动时执行 Java 类的最佳方法是什么?
最佳答案
不一定有“最佳”方式。像往常一样,有很多方法可以做到这一点,“最好的”就是最适合您的项目的方法:
- 如 cjstehno 所述,在 XML 中的 bean 元素上使用 init-method="..."
- 实现 Spring 的 InitializingBean界面。当部署在 ApplicationContext 中时,创建bean时会调用afterPropertiesSet()方法。
- 用 @PostConstruct 注释 bean 上的方法.同样,如果部署到 ApplicationContext,则在创建 bean 时将调用带注释的方法。
- 如果您的 bean 更像是要绑定(bind)到 Spring 生命周期的基础架构 bean,请实现 ApplicationListener < ContextRefreshedEvent >。 onApplicationEvent(..) 方法将在 Spring 启动期间被调用,您可以在那里做任何您需要的工作。
关于java - 使用 Spring MVC 在应用程序启动时执行 Java 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6684451/