Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What is the best way to execute a Java class at application startup using Spring MVC ?

like image 319
storm_buster Avatar asked Jul 13 '11 19:07

storm_buster


People also ask

How do I run a code after booting from spring boot?

Best way to execute block of code after Spring Boot application started is using PostConstruct annotation. Or also you can use command line runner for the same.

What happens when spring boot application starts?

Spring Boot automatically configures your application based on the dependencies you have added to the project by using @EnableAutoConfiguration annotation. For example, if MySQL database is on your classpath, but you have not configured any database connection, then Spring Boot auto-configures an in-memory database.


2 Answers

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.
like image 76
Ryan Stewart Avatar answered Sep 18 '22 12:09

Ryan Stewart


Assuming your context is loaded on startup, create a bean in your spring application context with an init method explicitly called out in the XML config (or implement Springs InitializingBean). If you have lazy-loading enabled you will need to make sure this bean is not lazy.

<bean name="starter" init-method="start" class="com.my.StarterBean" lazy="false" /> 

(please double-check the params in the docs).

If your context is not loaded on startup you can register an server context listener (part of Servlet API, not Spring).

like image 44
cjstehno Avatar answered Sep 19 '22 12:09

cjstehno