JdbcMetadataStore: initialize schema, but for Spring app NOT using Boot

331 Views Asked by At

Versions:

Spring: 5.2.16.RELEASE
Spring Integrations: 5.3.9.RELEASE
PostgreSQL: 13.x

I have implemented a pure Spring 5.x webapp; there is no Spring Boot.

I am using the JdbcMetadataStore and require that the PostgreSQL database be initialized with schema definitions located on the classpath in:

classpath:org/springframework/integration/jdbc/schema-postgresql.sql

Following a very useful article on the topic, here are properties I put in spring.properties:

spring.integration.jdbc.initialize-schema=always
spring.integration.jdbc.schema=classpath:org/springframework/integration/jdbc/schema-postgresql.sql

This DOES NOT work. After researching this issue, I have learned that the start-up initialization is supported, but in Spring Boot.

QUESTION: Short of explicitly handling the execution of this SQL script elsewhere during webapp initialization, is there any standard way to load the script listed above at start-up? NOTE: I am not using schema.sql scripts or similar to initialize my backend.

1

There are 1 best solutions below

2
On

See DataSourceInitializer in spring-jdbc:

/**
 * Used to {@linkplain #setDatabasePopulator set up} a database during
 * initialization and {@link #setDatabaseCleaner clean up} a database during
 * destruction.

 * @see DatabasePopulator
 */
public class DataSourceInitializer implements InitializingBean, DisposableBean {

You need to inject over there a ResourceDatabasePopulator based on that script location:

/**
 * Populates, initializes, or cleans up a database using SQL scripts defined in
 * external resources.
 *
 * <ul>
 * <li>Call {@link #addScript} to add a single SQL script location.
 * <li>Call {@link #addScripts} to add multiple SQL script locations.
 * <li>Consult the setter methods in this class for further configuration options.
 * <li>Call {@link #populate} or {@link #execute} to initialize or clean up the
 * database using the configured scripts.
 * </ul>
 *

 * @see DatabasePopulatorUtils
 * @see ScriptUtils
 */
public class ResourceDatabasePopulator implements DatabasePopulator {

Some docs are here: https://docs.spring.io/spring-framework/docs/current/reference/html/data-access.html#jdbc-initializing-datasource