【问题标题】:Spring Boot - run custom code before the DataSource bean is initializedSpring Boot - 在初始化 DataSource bean 之前运行自定义代码
【发布时间】:2018-01-04 15:39:41
【问题描述】:

如标题所示 - 在初始化 DataSource bean 之前,如何在我的 Spring Boot 应用程序中运行一些自定义代码?

我的 DataSource bean 的配置基于标准 spring.datasource.* 属性,所以这里没有什么不寻常的 - 我不手动创建 DataSource bean,而是依赖 Sprig Boot 的自动配置机制,如果可能的话,希望保持这种方式。

我想要实现的目标是在我的 Spring Boot 应用程序启动时使用 Cloud SQL Admin API Client Library for Java 配置一个 Google Cloud SQL 数据库实例,但在初始化 DataSource bean 之前,以便在实际创建这个 bean 时,数据库实例是已经在那里了。

谢谢

【问题讨论】:

    标签: java spring-boot google-cloud-platform


    【解决方案1】:

    您可以手动创建您的 DataSource bean,同时仍然大部分依赖 Spring Boots 自动配置。您需要做的就是指定spring.datasource 属性前缀

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
    
        // provision your Google Cloud SQL database instance here
    
        return DataSourceBuilder.create().build();
    }
    

    【讨论】:

    • 把函数改成@Component或者@Bean?
    • @e-info128 我不知道你在问什么
    猜你喜欢
    • 2012-07-21
    • 2020-03-02
    • 1970-01-01
    • 2011-01-27
    • 2011-12-05
    • 2020-11-22
    • 1970-01-01
    • 2016-11-10
    • 2018-09-02
    相关资源
    最近更新 更多