14

I have a Spring Boot 1.4.0 based Project that uses Liquibase.

Is it possible to execute a Method AFTER liquibase finished?

Something like Bean Post Processor?

What i want to do is adding some data to my database when the application is started in development mode. In developement mode the application uses an in-memory h2 database, so liquibase has to create the tables before i can write my data.

Yannic Bürgmann
  • 6,301
  • 5
  • 43
  • 77

2 Answers2

36

Spring Boot auto-configures a SpringLiquibase bean named liquibase. Any bean that depends on this bean will be created after Liquibase has finished. For example, you could use @PostConstruct to populate the database:

@Bean
@DependsOn("liquibase")
public YourBean yourBean() {
    return new YourBean();
}

static class YourBean {

    @PostConstruct
    public void populateDatabase() {
        System.out.println("This will be called after Liquibase has finished");
    }

}
Andy Wilkinson
  • 108,729
  • 24
  • 257
  • 242
  • Thanks :) Beautiful solution – Yannic Bürgmann Aug 09 '16 at 07:58
  • 1
    sorry for commenting on old question. What if `YourBean` and `liquibase` are on different threads ? I have the same use case and this solution does not work for me. Any idea ? – Amir Choubani Jan 25 '19 at 15:27
  • 2
    Application context refresh is single-threaded. How are you getting into a situation where the two beans are being initialized in parallel? – Andy Wilkinson Jan 25 '19 at 15:51
  • I am using jhipster. `liquibase` bean is initialized in other thread. https://github.com/jhipster/jhipster/blob/master/jhipster-framework/src/main/java/io/github/jhipster/config/liquibase/AsyncSpringLiquibase.java – Amir Choubani Jan 25 '19 at 16:02
  • 2
    As the javadoc of the class you've linked to says, you'll need to use the standard `SpringLiquibase` if you want to make database requests at startup. – Andy Wilkinson Jan 25 '19 at 20:19
  • I am facing an issue in multi-tenant application, when I create a database and run liquibase on it, the application restarts I don't know why. Do you have any idea how can I fix it? – Hafiz Hamza Feb 09 '22 at 10:30
2

Another solution would be to let LiquiBase insert these things into your database - but only when running in dev-mode.

You can do this in LiquiBase by specifying a context="" attribute.

Another option would be to let LiquiBase only insert this test-data into your database when dbms="h2db" (forgot what the exact string is to select h2, check documentation please!)

Both are attributes on changesets.

This is my own preferred solution for this kind of scenarios.