不一定是***的办法。像往常一样,有很多方法可以做到这一点,***的是最适合你项目的:
There's not necessarily a "best" way. As usual, there are many ways to do it, and the "best" is whichever fits into your project the best:
- 使用init-在XML中的bean元素上的method =...,如cjstehno提到的那样
- 实现Spring的 InitializingBean 接口。部署在 ApplicationContext ,在创建bean时将调用afterPropertiesSet()方法。
- 使用 @ PostConstruct 。同样,如果部署到ApplicationContext,则在创建bean时将调用带注释的方法。
- 如果您的bean更多是要绑定到Spring生命周期的基础结构bean,请实现 ApplicationListener < ContextRefreshedEvent >。 onApplicationEvent(..)方法将在Spring启动时调用,你可以在那里做任何你需要的工作。
- Use init-method="..." on a bean element in XML, as cjstehno mentioned
- Implement Spring's InitializingBean interface. When deployed in an ApplicationContext, the afterPropertiesSet() method will be called when the bean is created.
- Annotate a method on a bean with @PostConstruct. Again, if deployed to an ApplicationContext, the annotated method will be called when the bean is created.
- If your bean is more of an infrastructure bean to be tied into the Spring lifecycle, implement ApplicationListener<ContextRefreshedEvent>. The onApplicationEvent(..) method will be called during Spring's startup, and you can do whatever work you need there.