Executing a Java class at application startup using Spring MVC [duplicate]

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:

  1. Use init-method=”…” on a bean element in XML, as cjstehno mentioned
  2. Implement Spring’s InitializingBean interface. When deployed in an ApplicationContext, the afterPropertiesSet() method will be called when the bean is created.
  3. 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.
  4. 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.

Leave a Comment