2017-07-04 59 views
1

我使用flyway + hibernate驗證。我有飛路豆:如何在hibernate驗證之前啓動飛路遷移?

@Component 
public class DbMigration { 

    private static final Logger LOG = LoggerFactory.getLogger(DbMigration.class); 

    private final Config config; 

    @Autowired 
    public DbMigration(Config config) { 
     this.config = config; 
    } 

    public void runMigration() { 
     try { 
      Flyway flyway = new Flyway(); 
      flyway.configure(properties()); 
      int migrationApplied = flyway.migrate(); 
      LOG.info("[" + migrationApplied + "] migrations are applied"); 
     } catch (FlywayException ex) { 
      throw new DatabaseException("Exception during database migrations: ", ex); 
     } 
    } 

    public Properties properties() { 
     //my prop 
    } 
} 

而在Apllication類我做:

public static void main(String[] args) { 
     try { 
      AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class); 
      context.getBean(DbMigration.class).runMigration(); 

但我的休眠開始前runMigration();和驗證扔exeption。我如何從下一步開始?

  1. 運行遷移
  2. 啓動休眠驗證

編輯:

@Bean 
    @Autowired 
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource datasource) { 
     log.info("entityManagerFactory start"); 
     dbMigration.runMigration(); 

但我認爲這是壞的

+0

@Bean @DependsOn("flyway") public LocalContainerEntityManagerFactoryBean entityManagerFactory() { // Initialize EntityManagerFactory here } 

flyway bean配置可以是這樣的?如果是這樣,則不需要爲飛路遷移定義組件。如果你想覆蓋默認選項,並讓它在hibernate之前運行,像我在我的回答中解釋的那樣添加一個bean配置。您不需要告訴spring-boot來運行遷移,它會自動執行。 – Mustafa

回答

1

在Spring應用程序配置,如果你有一個實體經理工廠的bean配置,你可以使它依賴於flyway bean,使它成爲ge在它之後初始化。喜歡的東西:您是否使用'彈簧boot`

@Bean(initMethod = "migrate") 
public Flyway flyway() { 
    Flyway flyway = new Flyway(); 
    // configure bean here 
    return flyway; 
} 
+0

是的,我有LocalContainerEntityManagerFactoryBean,我得到「飛路」? – user5620472

+0

「飛路」是您的飛路豆的名稱。你可以像配置LocalContainerEntityManagerFactoryBean一樣來配置它。我會給我的答案添加一個例子。 – Mustafa