Spring Boot - 在类路径资源中定义名为'dataSource'的bean时出错

J.O*_*sen 55 java spring spring-boot

我有Spring Boot Web应用程序.它以RESTful方法为中心.所有配置似乎都存在但由于某种原因MainController无法处理请求.它导致404错误.怎么解决?

@Controller
public class MainController {

    @Autowired
    ParserService parserService;

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

应用

@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);
        }
}
Run Code Online (Sandbox Code Playgroud)

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(
   }
}
Run Code Online (Sandbox Code Playgroud)

UPDATE

似乎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.
Run Code Online (Sandbox Code Playgroud)

UPDATE2

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: /
Run Code Online (Sandbox Code Playgroud)

UPDATE4

似乎@RequestMapping设置了没有响应的轻型控制器.为什么会这样?

PS.它发生在我运行Maven的生命周期时test.在IntelliJ中以degub模式运行时,不会输出错误.

UPDATE5

我也使用这个DAO,如教程中所解释....

public interface RecordDao extends CrudRepository<Record, Long> {
}
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

Jas*_*ner 90

看起来最初的问题是auto-config.

如果您不需要数据源,只需将其从auto-config进程中删除:

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
Run Code Online (Sandbox Code Playgroud)

  • 有人应该让你成为一座纪念碑 (9认同)
  • 较新的 Spring Boot 版本:`@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})` (6认同)

小智 18

从事物的外观来看,你没有将足够的数据传递给Spring Boot来配置数据源

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

spring.datasource.driverClassName=
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
Run Code Online (Sandbox Code Playgroud)

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


Bab*_*i B 11

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

@SpringBootApplication(exclude = SqlInitializationAutoConfiguration.class)
Run Code Online (Sandbox Code Playgroud)

虽然它让服务器运行并且 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
Run Code Online (Sandbox Code Playgroud)

这是我找到的解决方案(有些已经是)将这些行添加到 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
Run Code Online (Sandbox Code Playgroud)

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

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

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


小智 10

也许你忘记了MySQL JDBC驱动程序.

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.34</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)


小智 6

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
Run Code Online (Sandbox Code Playgroud)

在 application.properties 中编写上面的行,它对我有用,以防 psql db 与 spring boot 3.0.3


Gau*_*and 5

我得到了同样的错误,发现它是由于我的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>
Run Code Online (Sandbox Code Playgroud)


小智 5

更改以下代码行

spring.datasource.driverClassName
Run Code Online (Sandbox Code Playgroud)

spring.datasource.driver-class-name
Run Code Online (Sandbox Code Playgroud)


Kum*_*hek 5

当您运行测试时会出现此问题。添加依赖

testCompile group: 'com.h2database', name: 'h2', version: '1.4.197' 
Run Code Online (Sandbox Code Playgroud)

在 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
Run Code Online (Sandbox Code Playgroud)

这将设置您的数据源。