Spring Web Application: doing something on startup (initialization)

13,219

Solution 1

Use the postconstuct annotation somewhere inside a bean :

@PostConstruct
public void init() {
     //startup logic here
}

Probably makes (desgin) sense to use a configuration bean, but it can be any bean at all.

Solution 2

You can create an application listener, it's designed specifically for such needs. In this case it will be executed every time context is started (or refreshed).

@Component
public class DatabaseFillerOnStartup implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ...
    }
}

Solution 3

Hibernate comes with an way to add some files with sql statements that will be executed on startup.

The parameter is hibernate.hbm2ddl.import_files.

@See Hibernate Reference: Chapter 3.4. Optional configuration properties

  • Table 3.7. Miscellaneous Properties
  • hibernate.hbm2ddl.import_files:

Comma-separated names of the optional files containing SQL DML statements executed during the SessionFactory creation. This is useful for testing or demoing: by adding INSERT statements for example you can populate your database with a minimal set of data when it is deployed.

File order matters, the statements of a give file are executed before the statements of the following files. These statements are only executed if the schema is created ie if hibernate.hbm2ddl.auto is set to create or create-drop.

e.g. /humans.sql,/dogs.sql

I fond some hints that this may only work if hibernate is started in 'create' mode. But I am not sure.

Share:
13,219
Fabio B.
Author by

Fabio B.

http://www.linkedin.com/in/fabiobozzo

Updated on June 15, 2022

Comments

  • Fabio B.
    Fabio B. almost 2 years

    I want to fill some tables of my DB from a text file on startup, I want my initialization method to be called only when my application do start.

    I am using Spring (+MVC) and Hibernate with MySQL.

    how can I do?