带有 Spring Boot 的 Flyway Core 给出错误“delayedFlywayInitializer”和“entityManagerFactory”之间的循环依赖关系

问题描述 投票:0回答:2

我想导入SQL Server数据库上的一些数据,我使用的是Spring Boot 2.3.4。我还使用 Hibernate 来生成表。

我在pom中添加了flyway核心:

 <dependency>
        <groupId>org.flywaydb</groupId>
        <artifactId>flyway-core</artifactId>
    </dependency>

创建配置文件:

import org.flywaydb.core.Flyway;
import org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer;
import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

@Configuration
public class FlyWayConfiguration {

    @Bean
    FlywayMigrationInitializer flywayInitializer(Flyway flyway) {
        return new FlywayMigrationInitializer(flyway, (f) ->{} );
    }
    
    @Bean
    @DependsOn("entityManagerFactory")
    FlywayMigrationInitializer delayedFlywayInitializer(Flyway flyway) {
        return new FlywayMigrationInitializer(flyway, new FlywayMigrationStrategy() {
            @Override
            public void migrate(Flyway flyway) {
            
                flyway.migrate();
            }
        });
    }
}

我在

resources/db/migration/V1_0_1__InitialData.sql

创建了一个文件

现在我遇到了这个错误

    Error creating bean with name 'delayedFlywayInitializer' defined in class path resource
    [com/ikun/mkj/config/MigrationConfiguration.class]: Circular depends-on relationship between
    'delayedFlywayInitializer' and 'entityManagerFactory' at 
org.springframework.beans.factory.support.AbstractBeanFactory

我不知道如何解决这个问题,我寻找解决方案但无法解决。 有人可以帮我吗?

sql-server spring database spring-boot flyway
2个回答
23
投票

您很可能通过添加以下内容来推迟数据源初始化:

spring.jpa.defer-datasource-initialization =true #set it to false

在您的应用程序中。[yml/properties]。

  • 删除它,或设置为 false 可以解决您的问题

如参考文献中所示: https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html

将 spring.jpa.defer-datasource-initialization 设置为 true。这会 将数据源初始化推迟到任何 EntityManagerFactory 之后 beans已经被创建并初始化。然后可以使用 schema.sql 对 Hibernate 执行的任何模式创建进行添加 data.sql 可用于填充它。

并且默认情况下 Flyway 依赖于 Datasource , defer 模式下的 Datasource 会等待 EntityManagerFactory 和 Ofc 因为我们使用 Flyway 默认是在 Jpa 之前启动 Flyway 以确保 DB 一致性

所以我们有一个循环依赖flyway->DS->EMF->Flyway


0
投票

起初我尝试了ameen的解决方案,但它本身并没有帮助。当我应用它时,Flyway 然后抱怨没有表可以运行 sql。

我最终不得不将以下内容添加到 application.properties:

spring.jpa.defer-datasource-initialization = false
spring.main.allow-circular-references = true
spring.flyway.depends-on = entityManagerFactory

额外的两行改变了初始化顺序,导致Flyway在entityManagerFactory之前初始化。

我想这与新版本相关。

这里是 Spring Boot 3.1.3。

附注这似乎仅适用于 Spring Boot 3.1.x 至 3.1.4。版本 3.1.5 和 3.0.9 无需添加这些设置即可工作。我相信这也只会影响 Spring Boot 2 的某些版本,因此简单的解决方案是如果可能的话关闭有问题的版本。

© www.soinside.com 2019 - 2024. All rights reserved.