I want to run some part of the code to populate the database with dummy data every time the server starts. I use Tomcat as my servlet container. My application is created using Spring. Is there a hook where I can run my code to populate the db just after my application is started?
-
What java framework are you using? – Salman Jul 12 '15 at 18:38
-
There are some listener for that, you could also use spring Smartlifecycle – Jul 12 '15 at 19:24
-
If you happen to be using Hibernate, naming your file import.sql and dropping it into your `resources` folder will automatically import the data. – riddle_me_this May 21 '17 at 00:42
2 Answers
You have two different alternatives.
The first one is using Spring's DataSourceInitializer
. You can pass your initialisation query as a parameter and it executes that query. You can execute any command that you like.
Example:
<bean id="dbInitializer" class="org.springframework.jdbc.datasource.init.DataSourceInitializer">
<property name="dataSource" ref="myDataSourceRef"/>
<property name="enabled" value="true"/>
<property name="databasePopulator">
<bean class="org.springframework.jdbc.datasource.init.ResourceDatabasePopulator">
<property name="continueOnError" value="true"/>
<property name="ignoreFailedDrops" value="true"/>
<property name="sqlScriptEncoding" value="UTF-8"/>
<property name="scripts">
<array>
<value type="org.springframework.core.io.Resource">init.sql</value>
</array>
</property>
</bean>
</property>
</bean>
The second alternative is implementing a Spring ApplicationListener
. Populate each datum from that listener to your database manually. It is a little harder to achieve.
Example:
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
public class ApplicationListenerBean implements ApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ContextRefreshedEvent) {
ApplicationContext applicationContext = ((ContextRefreshedEvent) event).getApplicationContext();
// now you can do applicationContext.getBean(...)
// ...
}
}
}
This bean must be initialised by Spring. You can either define it in your applicationContext.xml
or in your configuration class.
By the way, you can always listen for your ServletContext status by using a ServletContextListener
. But if you are using Spring, there are easier methods.

- 8,575
- 10
- 55
- 80

- 6,244
- 5
- 35
- 42
You can use Liquibase, and if you're using Spring Boot all you have to do is add liquibase-core
to your classpath, via maven or whatever build tool you're using is. Spring Boot uses YAML files by default. Spring Boot will then run Liquibase on every application startup.

- 16,274
- 24
- 118
- 243