簡體   English   中英

在 Spring Boot 中使用 PostgreSQL 驅動程序創建數據源時出現異常

[英]Exception when creating datasource with PostgreSQL driver in Spring Boot

我正在嘗試按照MKyong 的示例使用 Spring Boot 創建一個非 Web 應用程序,但出現以下錯誤:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.5.RELEASE)

(...) Several not relevant INFO log lines

2018-12-12 11:45:29.420 ERROR 30866 --- [ main] com.zaxxer.hikari.HikariConfig           : Failed to load driver class org.postgresql.Driver from HikariConfig class classloader sun.misc.Launcher$AppClassLoader@18b4aac2
2018-12-12 11:45:29.423  WARN 30866 --- [ main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'ldConfiguration': Could not bind properties to 'LdConfiguration' : prefix=datasources.ld, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'datasources.ld' to es.ortoplus.LdConfiguration$$EnhancerBySpringCGLIB$$625f0f64
2018-12-12 11:45:29.435  INFO 30866 --- [ main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-12-12 11:45:29.440 ERROR 30866 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to bind properties under 'datasources.ld' to es.oplus.LdConfiguration$$EnhancerBySpringCGLIB$$625f0f64:

    Property: datasources.ld.driverclassname
    Value: org.postgresql.Driver
    Origin: class path resource [application.yml]:3:22
    Reason: Failed to load driver class org.postgresql.Driver in either of HikariConfig class loader or Thread context classloader

Action:

Update your application's configuration

我的 conf 文件(application.yml)是

datasources:
  ld:
    driverClassName: org.postgresql.Driver
    jdbc-url: jdbc:postgresql://localhost:5432/oplus
    username: user123
    password: 123456
    connection-test-query: SELECT 1

在我的 Maven pom.xml 文件中,我添加了:

<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <!--<version> (managed by Spring Boot)42.2.5 </version> -->
</dependency>

我的入口點 class:

@SpringBootApplication
public class App implements CommandLineRunner {

    @Autowired private UsuarioRepository usuarioRep;
    @Override
    public void run(String... args) throws Exception {
        App app = new App();
        System.out.printf("Users: %1d", app.usuarioRep.count());

    }

    public static void main(String[] args) throws ClassNotFoundException {
        //Class.forName("org.postgresql.Driver");
        SpringApplication.run(App.class, args);

    }

}

如您所見,我已嘗試檢查 class 是否已在類路徑中。 如果我取消注釋該行,我會得到一個 ClassNotFoundException,所以錯誤似乎是因為 Maven 不包括依賴項。 我試圖將 scope 設置為runtime ,但它還是失敗了。

無論如何,這是我的配置 class:

@Configuration
@ConfigurationProperties(prefix = "datasources.ld")
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "postgreEntityManagerFactory", transactionManagerRef = "postgreTransactionManager",
        basePackages = "es.plus.l.dao")
public class LdConfiguration extends HikariConfig {

    @Bean(name = "postgreDataSource")
    @Primary
    public DataSource dataSource() {
        return new HikariDataSource(this);
    }

    @Bean(name = "postgreEntityManagerFactory")
    @Primary
    public LocalContainerEntityManagerFactoryBean postgreEntityManagerFactory(
            final EntityManagerFactoryBuilder builder,
            @Qualifier("postgreDataSource") final DataSource dataSource) {
        final LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setJpaVendorAdapter(this.vendorAdaptor());
        entityManagerFactoryBean.setDataSource(dataSource);
        entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        entityManagerFactoryBean.setPersistenceUnitName("postgre");
        entityManagerFactoryBean.setPackagesToScan("es.oplus.ld.model");
        entityManagerFactoryBean.setJpaProperties(this.jpaHibernateProperties());
        entityManagerFactoryBean.afterPropertiesSet();
        return entityManagerFactoryBean;
    }

    @Bean(name = "postgreTransactionManager")
    @Primary
    public PlatformTransactionManager postgreTransactionManager(
          @Qualifier("postgreEntityManagerFactory") final EntityManagerFactory emf) {
        return new JpaTransactionManager(emf);
    }

    private HibernateJpaVendorAdapter vendorAdaptor() {
        final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        // put all the adapter properties here, such as show sql
        return vendorAdapter;
    }

    private Properties jpaHibernateProperties() {
        final Properties properties = new Properties();
        // put all required jpa propeties here
        return properties;
    }

}

將下一個代碼添加到 pom.xml:

    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>

我發現了問題:Eclipse正確地顯示了依賴關系,但是因為它似乎並沒有真正存在,所以我嘗試手動運行它,所以當我執行時:

mvn clean install

我從Maven得到了這個錯誤

error reading /home/pablo/.m2/repository/org/postgresql/postgresql/42.2.5/postgresql-42.2.5.jar; invalid LOC header (bad signature)

因此,錯誤是由Maven下載jar的損壞版本引起的。

刪除它以強制新下載修復了該問題。

確保在 pom.xml 中同時具有 JDBC 驅動程序和 PostgreSQL 依賴項,如下所示:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency> 

在我的例子中,pom.xml 在依賴項下丟失了。 添加以下代碼,應該可以正常工作:

    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>

如果您使用的是 IntelliJ Idea,則重新啟動您的 IDE

暫無
暫無

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

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