Search code examples
javaspringtomcat7catalina

Populate a datasource during the start of the spring application


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?


Solution

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