簡體   English   中英

如何在 bean 運行之前延遲 Spring JPA 自動配置?

[英]How do I delay Spring JPA auto-configuration until a bean has run?

我有一個試圖連接到數據庫的 Spring 應用程序。 為了連接,必須首先建立一個 SSH 隧道(使用 Jsch)。 我如何延遲HibernateJpaAutoConfiguration直到建立 Jsch SSH 會話的 bean 返回之后? 當前應用程序無法啟動,因為隧道尚未打開。 當我嘗試排除這個自動配置類,然后根據已經創建的會話 bean 顯式實例化它時,我收到以下錯誤:

Caused by: java.lang.IllegalArgumentException: At least one JPA metamodel must be present!

我不明白為什么我突然必須自己提供這個,如果我依靠自動配置,我不必提供它。 如果有人可以向我展示實現這一目標的方法,那就太好了。

聚甲醛:

        ...
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!-- Spring data JPA, default tomcat pool, exclude it -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.tomcat</groupId>
                    <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        ...

主要應用:

@SpringBootApplication(exclude = HibernateJpaAutoConfiguration.class)
public class Application {
    public static void main(String... args) {
        SpringApplication.run(Application.class, args);
    }

    @Configuration
    static class SshTunnelConfiguration {
        @Bean
        public com.jcraft.jsch.Session sshTunnel() {
            ...
        }
    }

    @Configuration
    @ConditionalOnBean(com.jcraft.jsch.Session.class)
    static class DelayedJpaConfiguration extends HibernateJpaAutoConfiguration {
        public JpaConfiguration(DataSource dataSource, JpaProperties jpaProperties, ObjectProvider<JtaTransactionManager> jtaTransactionManager, ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
            super(dataSource, jpaProperties, jtaTransactionManager, transactionManagerCustomizers);
        }
    }
}

您必須實現自己的數據源(通過擴展您使用的數據源)並實現 InitializingBean 接口,並在“afterPropertiesSet”方法中初始化您的 jsch 隧道。

請參考: Spring Data JPA with ssh tunnel to a remote MySQL server

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM