Java Spring Boot - 创建名为“dataSource”的 bean 在类路径资源中定义时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28042426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:30:17  来源:igfitidea点击:

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

javaspringspring-boot

提问by J.Olufsen

I have Spring Boot web application. It's centered around RESTful approach. All configuration seems in place but for some reason MainController fails to handle request. It results in 404 error. How to fix it?

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

@Controller
public class MainController {

    @Autowired
    ParserService parserService;

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

Application

应用

@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(
   }
}

UPDATE

更新

Seems like MySQL cannot be initialized by Spring....

好像 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.

UPDATE2

更新2

application.properties

应用程序属性

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

更新4

Seems lite controllers not responding eventhough @RequestMappingare set. Why might it be?

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

PS. It occurs when I run Maven's lifecycle test. When running in degub mode in IntelliJ there is no error outputted.

附注。它发生在我运行 Maven 的生命周期时test。在 IntelliJ 中以调试模式运行时,不会输出错误。

UPDATE5

更新5

Also I use this DAO as explained in tutorial....

我也按照教程中的说明使用这个 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/

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

UPDATE6

更新6

I did changed my application properties. And tried every single combination but it refuses to work. ;(

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

Maven output:

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.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.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
0(ParentRunner.java:53) at org.junit.runners.ParentRunner.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.

采纳答案by Jason Warner

Looks like the initial problem is with the auto-config.

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

If you don't need the datasource, simply remove it from the auto-config process:

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

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

回答by Alan Barrows

From the looks of things you haven't passed enough data to Spring Boot to configure the datasource

从表面上看,您还没有将足够的数据传递给 Spring Boot 来配置数据源

Create/In your existing application.propertiesadd the following

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

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

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

making sure you append a value for each of properties.

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

回答by M. Deinum

The hibernate.*properties are useless, they should be spring.jpa.*properties. Not to mention that you are trying to override those already set by using the spring.jpa.*properties. (For the explanation of each property I strongly suggest a read of the Spring Boot reference guide.

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

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

Also the packages to scan are automatically detected based on the base package of your Applicationclass. If you want to specify something else use the @EntityScanannotation. Also specifying the most toplevel package isn't really wise as it will scan the whole class path which will severely impact performance.

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

回答by gcgan

Maybe you forgot the MySQL JDBC driver.

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

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

回答by Remy Mellet

Are you running the application as a jar? ( java -jar xxxx.jar)

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

If so, do you have the application.properties stored in that jar ?

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

If no, try to figure out why :

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

  • To be automatically package in the jar, the files can be in : src/main/resources/application.properties
  • The maven plugin in the pom.xml can also be configured
  • 要自动打包在jar中,文件可以在:src/main/resources/application.properties
  • pom.xml中的maven插件也可以配置

回答by AdrianVeidt

In my case this was happening because org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource is an autowired field without a Qualifier and I am using multiple datasources with qualified names. I solved this problem by using @Primary arbitrarily on one of my dataSource bean configurations like so

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

<!-- 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>

I suppose they want you to implement AbstractRoutingDataSource, and then that auto configuration will just work because no qualifier is needed, you just have a single data source that allows your beans to resolve to the appropriate DataSource as needed. Then you don't need the @Primary or @Qualifier annotations at all, because you just have a single DataSource.

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

In any case, my solution worked because my beans specify DataSource by qualifier, and the JPA auto config stuff is happy because it has a single primary DataSource. I am by no means recommending this as the "right" way to do things, but in my case it solved the problem quickly and did not deter the behavior of my application in any noticeable manner. Will hopefully one day get around to implementing the AbstractRoutingDataSource and refactoring all the beans that need a specific DataSource and then perhaps that will be a neater solution.

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

回答by Gaurav Anand

I was getting the same error, found out it was due to some of the dependencies missing in my pom.xml like that of Spring JPA, Hibernate, Mysql or maybe Hymanson. So make sure that dependencies are not missing in your pom.xml and check their version compatibility.

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

-DdevBaseDir="C:\Your_Project_Dir_Path"

回答by kazim

It worked for me you can try your: Add this to VM options in Tomcat

它对我有用,你可以试试你的:Add this to VM options in Tomcat

spring.datasource.driverClassName

回答by user6536363

change below line of code

更改以下代码行

spring.datasource.driver-class-name

to

##代码##

回答by Mahesh Japkar

I was facing this issue even after supplying all required datasource properties in application.properties. Then I realized that properties configuration class was not getting scanned by Spring boot because it was in different package hierarchy compared to my Spring boot Application.java and hence no properties were applied to datasource object. I changed the package name of my properties configuration class and it started working.

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