简体   繁体   中英

Spring Boot - run custom code before the DataSource bean is initialized

As in the title - how can I run some custom code in my Spring Boot application before the DataSource bean is initialized?

The configuration for my DataSource bean is based on the standard spring.datasource.* properties, so nothing unusual here - I don't create DataSource bean manually, but rather rely on Sprig Boot's auto-configuration mechanism and would like to leave it this way, if possible.

The goal I want to achieve is to provision a Google Cloud SQL database instance using Cloud SQL Admin API Client Library for Java when my Spring Boot application starts, but before the DataSource bean is initialized, so that when this bean is actually created, the database instance is already there.

Thanks

You can manually create your DataSource bean while still relying on Spring Boots auto-configuration for the most part. All you need to do is specify the spring.datasource property prefix

@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {

    // provision your Google Cloud SQL database instance here

    return DataSourceBuilder.create().build();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM