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:
- 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.