【问题标题】:Spring Boot - Error creating bean with name 'dataSource' defined in class path resourceSpring Boot - 在类路径资源中定义名称为“dataSource”的 bean 创建错误
【发布时间】:2015-03-18 12:13:00
【问题描述】:

我有 Spring Boot Web 应用程序。它以 RESTful 方法为中心。所有配置似乎都到位,但由于某种原因 MainController 无法处理请求。它会导致 404 错误。如何解决?

@Controller
public class MainController {

    @Autowired
    ParserService parserService;

    @RequestMapping(value="/", method= RequestMethod.GET)
    public @ResponseBody String displayStartPage(){
        return "{hello}";
    }
}

应用程序

@Configuration
@ComponentScan(basePackages = "")
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer{
        public static void main(final String[] args) {
            SpringApplication.run(Application.class, args);
        }

        @Override
        protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
            return application.sources(Application.class);
        }
}

ParserController

@RestController
public class ParserController {

    @Autowired
    private ParserService parserService;

    @Autowired
    private RecordDao recordDao;

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

    @RequestMapping(value="/upload", method= RequestMethod.POST)
    public @ResponseBody String fileUploadPage(
   }
}

更新

好像 MySQL 不能被 Spring 初始化......

    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Injection of autowired dependencies failed; 

nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; 

nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Instantiation of bean failed; 

nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; 

nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.

更新2

application.properties

    # Database 
    spring.datasource.driverClassName = com.mysql.jdbc.Driver
    spring.datasource.url = jdbc:mysql://localhost:3306/logparser
    spring.datasource.username = root
    spring.datasource.password = root
    
    spring.jpa.database = MYSQL
    spring.jpa.show-sql = true
    
    # Hibernate
    hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
    hibernate.show_sql: true
    hibernate.hbm2ddl.auto: update
    entitymanager.packagesToScan: /

UPDATE4

即使设置了@RequestMapping,似乎精简版控制器也没有响应。为什么会这样?

PS。它发生在我运行 Maven 的生命周期 test 时。 在 IntelliJ 中以 deub 模式运行时,没有输出错误。

UPDATE5

我也按照教程中的说明使用这个 DAO....

public interface RecordDao extends CrudRepository<Record, Long> {
}

http://blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/

UPDATE6

我确实更改了我的应用程序属性。并尝试了每一种组合,但它拒绝工作。 ;(

Maven 输出:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running IntegrationTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 2.365 sec <<< FAILURE! - in IntegrationTest
saveParsedRecordsToDatabase(IntegrationTest)  Time elapsed: 2.01 sec  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:331)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:213)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:290)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:292)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:264)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:124)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:200)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:153)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.

【问题讨论】:

  • 可以添加数据库配置吗?
  • 您将 yaml 和属性混合在一起。 hibernate.dialect: org.hibernate.dialect.MySQL5Dialect 将是 hibernate.dialect= org.hibernate.dialect.MySQL5Dialect
  • 按照您的建议进行了更改,但错误仍然存​​在
  • 它看起来像一个类路径问题。您对数据库有什么样的依赖关系,以及它是如何在 pom.xml 中定义的(例如,哪个范围等)。你能发布你的 pom.xml 吗?
  • 尝试从 UserDao 中删除 @Transactional

标签: java spring spring-boot


【解决方案1】:

看起来你没有向 Spring Boot 传递足够的数据来配置数据源

创建/在您现有的application.properties 中添加以下内容

spring.datasource.driverClassName=
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=

确保为每个属性附加一个值。

【讨论】:

  • 我已经有了那个文件和配置,虽然它与 spring.datasource.driver-class-name 和你的 spring.datasource.driverClassName 略有不同
  • 如果您将driver-class-name 的配置更改为driverClassName,它会起作用还是会出现其他错误?
  • @J.Olufsen 我认为driverClassName 改为type
【解决方案2】:

hibernate.* 属性没用,应该是spring.jpa.* 属性。更不用说您正在尝试使用 spring.jpa.* 属性覆盖已设置的那些。 (对于每个属性的解释,我强烈建议阅读 Spring Boot reference guide

spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql = true

# Hibernate
spring.jpa.hibernate.ddl-auto=update

还可以根据Application 类的基本包自动检测要扫描的包。如果您想指定其他内容,请使用 @EntityScan 注释。同样指定最顶层的包也不是很明智,因为它会扫描整个类路径,这将严重影响性能。

【讨论】:

  • 虽然我按照您的建议更改了属性,但出现了同样的错误。控制器也无法正常工作 (404 error)
  • 您的问题与原来的问题不同...找不到控制器与数据源无关。我建议标记解决您的数据源问题的答案并为控制器发布一个新的答案。
【解决方案3】:

也许您忘记了 MySQL JDBC 驱动程序。

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.34</version>
</dependency>

【讨论】:

    【解决方案4】:

    看起来最初的问题在于自动配置。

    如果您不需要数据源,只需将其从自动配置过程中删除:

    @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
    

    【讨论】:

    【解决方案5】:

    您是否将应用程序作为 jar 运行? (java -jar xxxx.jar)

    如果是这样,您是否将 application.properties 存储在该 jar 中?

    如果不是,请尝试找出原因:

    • 要自动打包到jar中,文件可以在:src/main/resources/application.properties
    • pom.xml中的maven插件也可以配置

    【讨论】:

      【解决方案6】:

      在我的情况下发生这种情况是因为 org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource 是一个没有限定符的自动装配字段,并且我正在使用多个具有限定名称的数据源。我通过在我的一个 dataSource bean 配置上任意使用 @Primary 解决了这个问题,就像这样

      @Primary
      @Bean(name="oneOfManyDataSources")
      public DataSource dataSource() { ... }
      

      我想他们希望您实现 AbstractRoutingDataSource,然后自动配置将正常工作,因为不需要限定符,您只有一个数据源,允许您的 bean 根据需要解析到适当的 DataSource。那么你根本不需要@Primary 或@Qualifier 注释,因为你只有一个DataSource。

      在任何情况下,我的解决方案都有效,因为我的 bean 通过限定符指定 DataSource,并且 JPA 自动配置内容很高兴,因为它有一个主 DataSource。我决不建议将此作为“正确”的做事方式,但就我而言,它很快解决了问题,并且没有以任何明显的方式阻止我的应用程序的行为。希望有一天能够实现 AbstractRoutingDataSource 并重构所有需要特定 DataSource 的 bean,然后也许这将是一个更简洁的解决方案。

      【讨论】:

        【解决方案7】:

        我遇到了同样的错误,发现这是由于我的 pom.xml 中缺少一些依赖项,例如 Spring JPA、Hibernate、Mysql 或 Jackson。 因此,请确保您的 pom.xml 中没有缺少依赖项并检查它们的版本兼容性。

        <!-- Jpa and hibernate -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.0.3.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        

        【讨论】:

          【解决方案8】:

          它对我有用,你可以试试你的: 将此添加到 Tomcat 中的 VM 选项中

          -DdevBaseDir="C:\Your_Project_Dir_Path"
          

          【讨论】:

            【解决方案9】:

            更改以下代码行

            spring.datasource.driverClassName
            

            spring.datasource.driver-class-name
            

            【讨论】:

            • 并在spring.datasource.type之前添加
            • application.yml 不在乎是驼峰式还是破折号式
            【解决方案10】:

            即使在 application.properties 中提供了所有必需的数据源属性后,我也遇到了这个问题。然后我意识到属性配置类没有被 Spring boot 扫描,因为与我的 Spring boot Application.java 相比,它位于不同的包层次结构中,因此没有属性应用于数据源对象。 我更改了我的属性配置类的包名称,它开始工作。

            【讨论】:

              【解决方案11】:

              如果您在 Spring Boot 应用程序中使用 application.properties,只需将以下行放入 application.properties 即可:
              spring.datasource.url: jdbc:mysql://google /?cloudSqlInstance=&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=****&password=****

              【讨论】:

                【解决方案12】:

                就我而言,我只是忽略了 application.properties 文件中的以下内容:

                #休眠

                #spring.jpa.hibernate.ddl-auto=update

                它对我有用....

                【讨论】:

                  【解决方案13】:

                  检查您在 build.gradle 的 runtime 组中是否具有数据库依赖项

                  runtime group: 'com.h2database', name: 'h2', version: '1.4.194'
                  

                  如果您使用 Maven,则将范围从测试更改为 运行时

                  <dependency>
                      <groupId>com.h2database</groupId>
                      <artifactId>h2</artifactId>
                      <version>1.4.194</version>
                      <scope>runtime</scope>
                  </dependency>
                  

                  【讨论】:

                    【解决方案14】:

                    给你点不一样的,遇到这种错误,无法创建 测试用例中的 bean 数据源。

                    可能是一些原因造成的:

                    1. 没有数据源,您需要创建数据源、h2 内存数据源等,或者您可以选择exclude={datasource··} 之类的方式。
                    2. 您有数据源,例如 MySQL,但它仍然无法正常工作。它是由AutoConfigureTestDatabase 类引起的,它会为您选择一个可能导致歧义的数据源。

                    解决方法:添加@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE),避免替换默认数据源。

                    【讨论】:

                      【解决方案15】:

                      与原始问题没有直接关系,但这对某人有用。这个错误发生在一个简单的两个项目结构中。一个项目正在使用 spring JDBC(比如 A)处理一些数据库操作,而另一个项目根本没有任何 JDBC 操作(比如 B)。但是,当我启动服务 B 时,仍然出现了这个错误。说数据源应该正确初始化。

                      我发现我已将此依赖项添加到两个模块的父 pom 中

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

                      这导致 spring 也为项目 B 初始化 JDBC 依赖项。所以,我把它移到了项目 A 的 pom 中,一切都很好。

                      希望这会对某人有所帮助

                      【讨论】:

                        【解决方案16】:

                        这个问题是在你运行测试时出现的。 添加依赖

                        testCompile group: 'com.h2database', name: 'h2', version: '1.4.197' 
                        

                        在test source下添加文件夹资源添加文件bootstrap.yml 并提供内容。

                        spring:
                          datasource:
                            type: com.zaxxer.hikari.HikariDataSource
                            url: jdbc:h2:mem:TEST
                            driver-class-name: org.h2.Driver
                            username: username
                            password: password
                            hikari:
                              idle-timeout: 10000
                        

                        这将设置您的数据源。

                        【讨论】:

                          【解决方案17】:

                          我这几天都遇到同样的问题,最后不是代码问题,问题来自maven,你必须删除他从你的硬盘下载的所有文件“C:\用户\用户名.m2\repository",并为您的项目执行另一个更新 maven,这将解决您的问题。

                          【讨论】:

                            【解决方案18】:

                            我通过更改父 Spring Boot Dependency 解决了我的问题。

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

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

                            有关更多信息,请查看发行说明:Spring Boot 2.1.0 Release Notes

                            【讨论】:

                              【解决方案19】:

                              在 MySQL 中创建数据库

                              create database springboot2;
                              

                              application.properties

                              spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
                              spring.datasource.url = jdbc:mysql://localhost:3306/springboot2
                              spring.datasource.username = root
                              spring.datasource.password = root
                              spring.jpa.show-sql = true
                              spring.jpa.hibernate.ddl-auto = update
                              spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
                              server.port=9192
                              

                              pom.xml

                              <dependencies>
                                      <dependency>
                                          <groupId>org.springframework.boot</groupId>
                                          <artifactId>spring-boot-starter-data-jpa</artifactId>
                                      </dependency>
                                      <dependency>
                                          <groupId>org.springframework.boot</groupId>
                                          <artifactId>spring-boot-starter-web</artifactId>
                                      </dependency>
                              
                                      <dependency>
                                          <groupId>mysql</groupId>
                                          <artifactId>mysql-connector-java</artifactId>
                                          <scope>runtime</scope>
                                      </dependency>
                                      <dependency>
                                          <groupId>org.projectlombok</groupId>
                                          <artifactId>lombok</artifactId>
                                          <optional>true</optional>
                                      </dependency>
                                      <dependency>
                                          <groupId>org.springframework.boot</groupId>
                                          <artifactId>spring-boot-starter-test</artifactId>
                                          <scope>test</scope>
                                          <exclusions>
                                              <exclusion>
                                                  <groupId>org.junit.vintage</groupId>
                                                  <artifactId>junit-vintage-engine</artifactId>
                                              </exclusion>
                                          </exclusions>
                                      </dependency>
                                  </dependencies>
                              

                              主类

                              import org.springframework.boot.SpringApplication;
                              import org.springframework.boot.autoconfigure.SpringBootApplication;
                              
                              @SpringBootApplication
                              public class Application {
                              
                                  public static void main(String[] args) {
                                      SpringApplication.run(Application.class, args);
                                  }
                              
                              }
                              

                              模型类

                              package com.First.Try.springboot.entity;
                                  
                              import javax.persistence.Entity;
                              import javax.persistence.GeneratedValue;
                              import javax.persistence.Id;
                              import javax.persistence.Table;
                              
                              import lombok.AllArgsConstructor;
                              import lombok.Data;
                              import lombok.NoArgsConstructor;
                              @Data
                              @AllArgsConstructor 
                              @NoArgsConstructor
                              @Entity
                              @Table(name="PRODUCT_TBL1")
                              public class Product {
                                  @Id
                                  @GeneratedValue
                                  private int id;
                                  private String name;
                                  private int quantity;
                                  private double price;
                                  ....
                                  ....
                                  ....
                               }
                              

                              【讨论】:

                                【解决方案20】:

                                默认情况下,使用最新版本的 Spring Boot,data.sql 的加载是在创建表之前完成的。所以使用 - spring.jpa.defer-datasource-initialization=true

                                例子-

                                **In application.properties :- **
                                spring.jpa.show-sql=true
                                spring.datasource.url=jdbc:h2:mem:testdb
                                spring.h2.console.enabled=true
                                spring.jpa.defer-datasource-initialization=true
                                

                                谢谢 阿塔尔·卡里姆

                                【讨论】:

                                • 我在使用 H2 作为我正在开发的 Spring Boot 应用程序的数据库时遇到了同样的问题。经过一番研究,将此spring.jpa.defer-datasource-initialization=true 配置添加到 application.properties 文件解决了我的问题。您的解释与此 roytuts.com/integrate-h2-in-memory-database-with-spring-boot 相同
                                【解决方案21】:

                                我正在使用 Spring Boot 2.6.0 我尝试了几个答案,但还不够。 我发现的一个临时解决方案是这个

                                @SpringBootApplication(exclude = SqlInitializationAutoConfiguration.class)
                                

                                虽然它允许服务器运行并且 h2-console 出现,但我无法连接到我的 data.sql 文件。这是我得到的错误

                                Database "mem:testdb" not found, either pre-create it or allow remote database creation (not recommended in secure environments) [90149-200] 90149/90149
                                

                                这是我找到的解决方案 (有些已经)将这些行添加到 application.properties 文件中

                                spring.jpa.show-sql=true
                                spring.h2.console.enabled=true
                                spring.datasource.url=jdbc:h2:mem:testdb
                                spring.jpa.defer-datasource-initialization=true
                                

                                保存重新运行服务器,然后尝试从 h2 控制台再次访问浏览器上的数据库

                                默认情况下,data.sql 脚本现在在 Hibernate 初始化之前运行。这使基于脚本的基本初始化行为与 Flyway 和 Liquibase 的行为保持一致。如果要使用 data.sql 填充 Hibernate 创建的模式,请将 spring.jpa.defer-datasource-initialization 设置为 true。

                                spring.jpa.defer-datasource-initialization=true 解决问题

                                【讨论】:

                                  【解决方案22】:

                                  我没有在pom文件中使用h2配置,我已经添加了,这个问题解决了。

                                  <dependency>
                                          <groupId>com.h2database</groupId>
                                          <artifactId>h2</artifactId>
                                          <scope>runtime</scope>
                                      </dependency>
                                  

                                  【讨论】:

                                    猜你喜欢
                                    • 2021-06-28
                                    • 2017-03-02
                                    • 1970-01-01
                                    • 2021-08-20
                                    • 1970-01-01
                                    • 2015-10-16
                                    • 2019-01-22
                                    • 2019-08-17
                                    相关资源
                                    最近更新 更多