【问题标题】:After Spring Boot 2.0 migration: jdbcUrl is required with driverClassNameSpring Boot 2.0 迁移后:需要 jdbcUrl 和 driverClassName
【发布时间】:2018-08-11 19:58:48
【问题描述】:

已解决: 我的解决方案:我从 DatabaseConfig.java 中删除 dataSource() 方法。然后,应用程序启动成功:)

我刚刚将我的 Spring Boot 项目从 1.5.x 更新到 2.0.0。在更新之前,此应用程序可以正常运行,但在更新之后,我收到一些错误如下。什么问题,你能帮帮我吗?

我在项目中使用 PostgreSQL、Hibernate、JPA。

我也尝试过this,但它对我不起作用。

感谢您的宝贵时间 :)

这里有问题:

2018-03-03 23:19:37.934 ERROR 42323 --- [           main] com.zaxxer.hikari.HikariConfig           : HikariPool-1 - dataSource or dataSourceClassName or jdbcUrl is required.
2018-03-03 23:19:37.938  WARN 42323 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.IllegalArgumentException: dataSource or dataSourceClassName or jdbcUrl is required.
2018-03-03 23:19:37.939  INFO 42323 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2018-03-03 23:19:37.954  INFO 42323 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-03-03 23:19:37.963 ERROR 42323 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.IllegalArgumentException: dataSource or dataSourceClassName or jdbcUrl is required.
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:729) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:470) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1250) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1085) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:858) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:388) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1234) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    at com.Test.Test.TestApplication.main(TestApplication.java:17) [classes/:na]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.IllegalArgumentException: dataSource or dataSourceClassName or jdbcUrl is required.
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:729) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:470) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1250) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:815) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:721) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    ... 19 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.IllegalArgumentException: dataSource or dataSourceClassName or jdbcUrl is required.
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:587) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1250) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:815) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:721) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    ... 33 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.IllegalArgumentException: dataSource or dataSourceClassName or jdbcUrl is required.
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:579) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    ... 46 common frames omitted
Caused by: java.lang.IllegalArgumentException: dataSource or dataSourceClassName or jdbcUrl is required.
    at com.zaxxer.hikari.HikariConfig.validate(HikariConfig.java:1063) ~[HikariCP-2.7.8.jar:na]
    at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:109) ~[HikariCP-2.7.8.jar:na]
    at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:151) ~[spring-jdbc-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:115) ~[spring-jdbc-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:78) ~[spring-jdbc-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:318) ~[spring-jdbc-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:355) ~[spring-jdbc-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.boot.autoconfigure.orm.jpa.DatabaseLookup.getDatabase(DatabaseLookup.java:72) ~[spring-boot-autoconfigure-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    at org.springframework.boot.autoconfigure.orm.jpa.JpaProperties.determineDatabase(JpaProperties.java:168) ~[spring-boot-autoconfigure-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    at org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.jpaVendorAdapter(JpaBaseConfiguration.java:111) ~[spring-boot-autoconfigure-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration$$EnhancerBySpringCGLIB$$738c1df5.CGLIB$jpaVendorAdapter$3(<generated>) ~[spring-boot-autoconfigure-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration$$EnhancerBySpringCGLIB$$738c1df5$$FastClassBySpringCGLIB$$beb7cb58.invoke(<generated>) ~[spring-boot-autoconfigure-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration$$EnhancerBySpringCGLIB$$738c1df5.jpaVendorAdapter(<generated>) ~[spring-boot-autoconfigure-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    ... 47 common frames omitted


Process finished with exit code 1

这是我的 pom.xml:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
</parent>

<properties>
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
       <java.version>1.9</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-properties-migrator</artifactId>
    </dependency>
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
    </dependency>
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
    </dependency>
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
    </dependency>
    <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
    </dependency>
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
            <version>1.4.3.RELEASE</version>
    </dependency>
</dependencies>

这是我的 application.yml:

spring:
  application:
    name: Test

  jpa:
    hibernate:
      ddl-auto: update
      use-new-id-generator-mappings: true
    generate-ddl: true
    properties:
      dialect: org.hibernate.dialect.PostgreSQLDialect

  session:
    store-type: none

  datasource:
    driverClassName: org.postgresql.Driver
    url: jdbc:postgresql://localhost:5432/test
    username: test
    password: 1234

    tomcat:
      max-idle: 2
      max-active: 3
    type: com.zaxxer.hikari.HikariDataSource

更新:

我的 DatabaseConfig.java:

@Configuration
public class DatabaseConfig {
    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() { return DataSourceBuilder.create().build(); }

    @Bean
    public SimpleMailMessage templateSimpleMessage() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setText(
                "This is the test email template for your email:\n%s\n");
        return message;
    }
}

【问题讨论】:

  • 您确定您的application.yml 格式正确吗?我不希望 tomcat 成为 datasource 的子元素
  • 是的,我很确定。这也不是问题,因为在 1.5.x 中没有问题。谢谢:)
  • 那是tomcat连接池(1.5默认)。该 yaml 的最后 4 行作为 Spring Boot 2 switched to Hikari by default 无用,配置另一个连接池的实现将无效。例外很奇怪。您是否在代码中自己配置数据源?可以分享一下样品吗?
  • @StephaneNic​​oll 首先感谢您的回答。我将删除 application.yml 中不必要的行。我已将我的数据库配置类插入到 UPDATE 标题下方的帖子中。
  • 我刚刚修复它,感谢您的所有积极响应。我还从 DatabaseConfig.java 中删除了 dataSource() 方法。然后,应用程序启动成功:)

标签: java spring spring-boot


【解决方案1】:

由于这篇文章有点受欢迎,我对其进行了一些编辑。 Spring Boot 2.x.x 将 default JDBC 连接池从 Tomcat 更改为更快更好的 HikariCP。这是不兼容的,因为 HikariCP 使用 jdbc url 的不同属性。有两种处理方式:

选项一

春天有很好的解释和解决方法docs

此外,如果您碰巧在类路径中有 Hikari,则此基本设置不起作用,因为 Hikari 没有 url 属性(但有 jdbcUrl 属性)。在这种情况下,您必须按如下方式重写您的配置:

app.datasource.jdbc-url=jdbc:mysql://localhost/test
app.datasource.username=dbuser
app.datasource.password=dbpass

选项二

文档中还有如何让它从“两个世界”工作的方法。它看起来像下面。 ConfigurationProperties bean 将为 jdbcUrlapp.datasource.url 进行“转换”

@Configuration
public class DatabaseConfig {
    @Bean
    @ConfigurationProperties("app.datasource")
    public DataSourceProperties dataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @ConfigurationProperties("app.datasource")
    public HikariDataSource dataSource(DataSourceProperties properties) {
        return properties.initializeDataSourceBuilder().type(HikariDataSource.class)
                .build();
    }
}

【讨论】:

  • 谢谢!从 app.datasource.url 重命名为 app.datasource.jdbc-url 解决了我的问题。
  • 我得到两个字符串的“重复前缀”作为参数传递给 ConfigurationProperties。有什么改变来做到这一点吗?
  • 确实,将 datasource.url 重命名为 datasource.jdbc-url 也解决了我的问题,谢谢
  • 遇到了与@acarlstein 提到的相同的问题。第二种方法中的“属性”参数也有问题:“无法自动装配。有多个 'DataSourceProperties' 类型的 bean。”
【解决方案2】:

这发生在我身上,因为我正在使用:

app.datasource.url=jdbc:mysql://localhost/test

当我将 url 替换为 jdbc-url 时,它起作用了:

app.datasource.jdbc-url=jdbc:mysql://localhost/test

【讨论】:

  • 这个答案完全可以正常工作。无需任何额外代码即可使其成为可接受的答案。
  • 在 2.1.5.release 上验证。与 jdbc-url 一起工作正常。网址不再起作用。
  • 像魅力一样工作。在 2.2.5.RELEASE 上验证
【解决方案3】:

如果您确实需要定义dataSource(),例如当您有多个数据源时,您可以使用:

@Autowired Environment env;

@Primary
@Bean
public DataSource customDataSource() {

    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getProperty("custom.datasource.driver-class-name"));
    dataSource.setUrl(env.getProperty("custom.datasource.url"));
    dataSource.setUsername(env.getProperty("custom.datasource.username"));
    dataSource.setPassword(env.getProperty("custom.datasource.password"));

    return dataSource;

}

通过自己设置dataSource(而不是使用DataSourceBuilder),它解决了我的问题,你也有。

知识渊博的Baeldung 有教程深入讲解。

【讨论】:

  • 解决了他的问题,碰巧在使用多个数据源时也很有用。
  • 是的,它偶尔会解决问题 - 但是 Spring Data 很大程度上建立在约定优于配置的原则上,因此它应该可以在不需要代码的情况下解决 :) 您的解决方案非常适合多个数据库,我会记住这一点,尽管我不希望进入这样一种情况,即我在一个应用程序/微服务中确实需要 3 个不同的数据库(本地 H2 + Staging-Database + 某个地方的第 3 个数据库)。
  • 应根据有关如何处理多个来源的文档改进已接受的答案 - docs.spring.io/spring-boot/docs/current/reference/htmlsingle/…
【解决方案4】:

我还阅读了 Spring 文档,正如 lapkritinis 建议的那样——幸运的是,这让我走上了正确的道路!但我不认为 Spring 文档现在可以很好地解释这一点。至少对我来说,他们并不一致恕我直言。

最初的问题是,如果您将现有的 Spring Boot 1.5.x 应用程序升级到使用 PostgreSQL/Hibernate 的 2.0.x,该怎么办。您得到描述的错误的主要原因是that Spring Boot 2.0.x uses HikariCP instead of Tomcat JDBC pooling DataSource as a default - 而Hikari 的DataSource 不知道spring.datasource.url 属性,而是希望拥有spring.datasource.jdbc-urllapkritinis 也指出了这一点)。

到目前为止一切顺利。但是文档也建议 - 这就是这里的问题 - Spring Boot 使用spring.datasource.url 来确定@​​987654324@:

您至少应该通过设置 spring.datasource.url 属性。否则,Spring Boot 会尝试 自动配置嵌入式数据库。

您可能会看到两难境地。如果您想像以前一样拥有嵌入式数据库,则必须切换回 Tomcat JDBC。 这对现有应用程序的侵入性也小得多,因为您不必更改源代码! 在 Spring Boot 1.5.x --> 2.0.x 升级后让现有应用程序正常工作PostgreSQL,只需添加 tomcat-jdbc 作为 pom.xml 的依赖项:

    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-jdbc</artifactId>
    </dependency>

然后配置 Spring Boot 以在 application.properties 中相应地使用它:

spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource

希望能帮助一些人解决这个问题,这是一个相当耗时的问题。我也希望我心爱的 Spring 人员更新文档 - 以及新 Hikari 池的配置方式 - 以获得更一致的 Spring Boot 用户体验:)

【讨论】:

  • 关于到底发生了什么的非常翔实的答案!
  • HikariCP应该比Tomcat好
  • 感谢@jonashackt 它帮助了我。
【解决方案5】:

这对我有用。

application.properties,使用 jdbc-url 而不是 url

datasource.apidb.jdbc-url=jdbc:mysql://localhost:3306/apidb?useSSL=false
datasource.apidb.username=root
datasource.apidb.password=123
datasource.apidb.driver-class-name=com.mysql.jdbc.Driver

配置类:

@Configuration
@EnableJpaRepositories(
        entityManagerFactoryRef = "fooEntityManagerFactory",
        basePackages = {"com.buddhi.multidatasource.foo.repository"}
)
public class FooDataSourceConfig {

    @Bean(name = "fooDataSource")
    @ConfigurationProperties(prefix = "datasource.foo")
    public HikariDataSource dataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean(name = "fooEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean fooEntityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("fooDataSource") DataSource dataSource
    ) {
        return builder
                .dataSource(dataSource)
                .packages("com.buddhi.multidatasource.foo.model")
                .persistenceUnit("fooDb")
                .build();
    }
}

【讨论】:

    【解决方案6】:

    Spring Boot 2.0.*或以上配置两个DataSource

    如果您需要配置多个数据源,则必须将其中一个 DataSource 实例标记为 @Primary,因为未来的各种自动配置都希望能够按类型获得一个.

    如果您创建自己的数据源,则自动配置会退出。在以下示例中,我们提供了与自动配置在主数据源上提供的完全相同的功能集:

    @Bean
    @Primary
    @ConfigurationProperties("app.datasource.first")
    public DataSourceProperties firstDataSourceProperties() {
        return new DataSourceProperties();
    }
    
    @Bean
    @Primary
    @ConfigurationProperties("app.datasource.first")
    public DataSource firstDataSource() {
        return firstDataSourceProperties().initializeDataSourceBuilder().build();
    }
    
    @Bean
    @ConfigurationProperties("app.datasource.second")
    public BasicDataSource secondDataSource() {
        return DataSourceBuilder.create().type(BasicDataSource.class).build();
    }
    

    firstDataSourceProperties 必须标记为 @Primary,以便数据库初始化程序功能使用您的副本(如果您使用初始化程序)。

    您的application.propoerties 将如下所示:

    app.datasource.first.url=jdbc:oracle:thin:@localhost/first
    app.datasource.first.username=dbuser
    app.datasource.first.password=dbpass
    app.datasource.first.driver-class-name=oracle.jdbc.OracleDriver
    
    app.datasource.second.url=jdbc:mariadb://localhost:3306/springboot_mariadb
    app.datasource.second.username=dbuser
    app.datasource.second.password=dbpass
    app.datasource.second.driver-class-name=org.mariadb.jdbc.Driver
    

    以上方法是spring boot 2.0及以上版本初始化多数据库的正确方法。更多阅读可以找到here

    【讨论】:

    • 使用 spring-boot 2.1.4(最新版本) 当您有两个具有不同驱动程序的不同数据源时,此方法不起作用。一个使用 jdbc MariDB 驱动程序,另一个使用 ibm DB2Driver...
    • @S34N 我已经更新了我的答案,希望这能解决您的问题。
    【解决方案7】:

    我已经在应用类中添加了

    @Bean
    @ConfigurationProperties("app.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }
    

    application.properties 我已经添加了

    app.datasource.url=jdbc:mysql://localhost/test
    app.datasource.username=dbuser
    app.datasource.password=dbpass
    app.datasource.pool-size=30
    

    更多详情Configure a Custom DataSource

    【讨论】:

      【解决方案8】:

      其他人已经回答了,所以我将添加我的 2 美分。

      您可以使用自动配置(即不使用 @Configuration 创建数据源)或 java 配置。

      自动配置:

      定义您的数据源类型,然后设置类型属性。例如

      spring.datasource.type=com.zaxxer.hikari.HikariDataSource
      spring.datasource.hikari.driver-class-name=org.h2.Driver
      spring.datasource.hikari.jdbc-url=jdbc:h2:mem:testdb
      spring.datasource.hikari.username=sa
      spring.datasource.hikari.password=password
      spring.datasource.hikari.max-wait=10000
      spring.datasource.hikari.connection-timeout=30000
      spring.datasource.hikari.idle-timeout=600000
      spring.datasource.hikari.max-lifetime=1800000
      spring.datasource.hikari.leak-detection-threshold=600000
      spring.datasource.hikari.maximum-pool-size=100
      spring.datasource.hikari.pool-name=MyDataSourcePoolName
      

      Java 配置:

      选择一个前缀并定义您的数据源

      spring.mysystem.datasource.type=com.zaxxer.hikari.HikariDataSource
      spring.mysystem.datasource.jdbc- 
      url=jdbc:sqlserver://databaseserver.com:18889;Database=MyDatabase;
      spring.mysystem.datasource.username=dsUsername
      spring.mysystem.datasource.password=dsPassword
      spring.mysystem.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
      spring.mysystem.datasource.max-wait=10000
      spring.mysystem.datasource.connection-timeout=30000
      spring.mysystem.datasource.idle-timeout=600000
      spring.mysystem.datasource.max-lifetime=1800000
      spring.mysystem.datasource.leak-detection-threshold=600000
      spring.mysystem.datasource.maximum-pool-size=100
      spring.mysystem.datasource.pool-name=MySystemDatasourcePool
      

      创建您的数据源 bean:

      @Bean(name = { "dataSource", "mysystemDataSource" })
      @ConfigurationProperties(prefix = "spring.mysystem.datasource")
      public DataSource dataSource() {
          return DataSourceBuilder.create().build();
      }
      

      您可以忽略数据源类型,但您可能会猜测要使用哪种数据源类型。

      【讨论】:

        【解决方案9】:

        您可以为此目的使用 DataSourceBuilder。

        @Primary
        @Bean(name = "dataSource")
        @ConfigurationProperties(prefix = "spring.datasource")
        public DataSource dataSource(Environment env) {
            final String datasourceUsername = env.getRequiredProperty("spring.datasource.username");
            final String datasourcePassword = env.getRequiredProperty("spring.datasource.password");
            final String datasourceUrl = env.getRequiredProperty("spring.datasource.url");
            final String datasourceDriver = env.getRequiredProperty("spring.datasource.driver-class-name");
            return DataSourceBuilder
                    .create()
                    .username(datasourceUsername)
                    .password(datasourcePassword)
                    .url(datasourceUrl)
                    .driverClassName(datasourceDriver)
                    .build();
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-08-27
          • 2018-09-12
          • 2021-05-21
          • 2018-09-18
          • 1970-01-01
          • 2018-01-09
          相关资源
          最近更新 更多