一个组件需要一个名为“dataSource”的 bean,但找不到该 bean
Posted
技术标签:
【中文标题】一个组件需要一个名为“dataSource”的 bean,但找不到该 bean【英文标题】:A component required a bean named 'dataSource' that could not be found 【发布时间】:2020-09-10 16:34:56 【问题描述】:我正在使用 Spring Boot 开发一个简单的 Spring Batch jar。我已经使用 Configuration 类来创建 dataSource bean 并使用 @Component 进行注释。但是当我使用 CommandLine Runner 运行应用程序时,它会在读取 ABPBatchInfrastructure.xml 时抛出 bean not found 异常。
我在 google 中对此错误进行了一些研究并找到了解决方案,我在 ABPBatchInfrastructure.xml 中添加了以下行
<context:component-scan base-package="com.abp.printbatch"></context:component-scan>
添加此行已解决问题,但有其他副作用
Spring 加载了两次,所有的 spring 核心 bean 都被实例化了两次。 我通过检查日志发现了这一点。下面的日志供参考,其中两次显示相同的行。
即使在 application-dev.properties 中添加 spring.jpa.properties.hibernate.format_sql=true 后,Spring JPA SQL 语句也不会显示在控制台中。
有没有办法通过删除 xml 中的组件扫描来仅实例化一次 spring,并修复未找到数据源 bean 的问题。请指导我。下面的日志供您参考,清楚地显示弹簧正在加载两次。
2020-05-23 16:04:06.976 INFO 90732 --- [ main] c.a.p.FileUploadApplication : Starting FileUploadApplication on MW7CH1-FZXX with PID 90732 (C:\gitforABP\SpringBatch\target\classes started by cac6584 in C:\gitforABP\SpringBatch)
2020-05-23 16:04:06.979 INFO 90732 --- [ main] c.a.p.FileUploadApplication : The following profiles are active: dev
2020-05-23 16:04:07.672 INFO 90732 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-23 16:04:07.752 INFO 90732 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 69ms. Found 1 JPA repository interfaces.
2020-05-23 16:04:08.161 INFO 90732 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-05-23 16:04:08.165 WARN 90732 --- [ main] com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=oracle.jdbc.driver.OracleDriver was not found, trying direct instantiation.
2020-05-23 16:04:08.819 INFO 90732 --- [ main] com.zaxxer.hikari.pool.PoolBase : HikariPool-1 - Driver does not support get/set network timeout for connections. (Receiver class oracle.jdbc.driver.T4CConnection does not define or inherit an implementation of the resolved method abstract getNetworkTimeout()I of interface java.sql.Connection.)
2020-05-23 16:04:08.870 INFO 90732 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-05-23 16:04:08.923 INFO 90732 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-05-23 16:04:09.006 INFO 90732 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.12.Final
2020-05-23 16:04:09.152 INFO 90732 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations 5.1.0.Final
2020-05-23 16:04:09.312 INFO 90732 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
2020-05-23 16:04:10.351 INFO 90732 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-05-23 16:04:10.364 INFO 90732 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-05-23 16:04:10.771 INFO 90732 --- [ main] c.a.p.FileUploadApplication : Started FileUploadApplication in 4.167 seconds (JVM running for 5.839)
2020-05-23 16:04:10.772 INFO 90732 --- [ main] c.a.p.FileUploadApplication : Local
2020-05-23 16:04:11.186 INFO 90732 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-23 16:04:11.206 INFO 90732 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 19ms. Found 1 JPA repository interfaces.
2020-05-23 16:04:11.298 INFO 90732 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Starting...
2020-05-23 16:04:11.298 WARN 90732 --- [ main] com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=oracle.jdbc.driver.OracleDriver was not found, trying direct instantiation.
2020-05-23 16:04:11.663 INFO 90732 --- [ main] com.zaxxer.hikari.pool.PoolBase : HikariPool-2 - Driver does not support get/set network timeout for connections. (Receiver class oracle.jdbc.driver.T4CConnection does not define or inherit an implementation of the resolved method abstract getNetworkTimeout()I of interface java.sql.Connection.)
2020-05-23 16:04:11.691 INFO 90732 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Start completed.
2020-05-23 16:04:11.706 INFO 90732 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-05-23 16:04:11.714 INFO 90732 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
2020-05-23 16:04:12.150 INFO 90732 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-05-23 16:04:12.151 INFO 90732 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-05-23 16:04:12.170 INFO 90732 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: ORACLE
2020-05-23 16:04:12.264 INFO 90732 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2020-05-23 16:04:12.465 WARN 90732 --- [ main] o.s.b.a.batch.JpaBatchConfigurer : JPA does not support custom isolation levels, so locks may not be taken when launching Jobs
2020-05-23 16:04:12.467 INFO 90732 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: ORACLE
2020-05-23 16:04:12.467 INFO 90732 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
入口点
@SpringBootApplication
@ComponentScan(basePackages = "com.abp.printbatch")
public class FileUploadApplication extends PrintBatchConstants implements CommandLineRunner
@Autowired
private NotifyYaml notify;
final static Logger logger = LoggerFactory.getLogger(FileUploadApplication.class);
public static void main(String[] args)
SpringApplication application = new SpringApplication(FileUploadApplication.class);
application.setBannerMode(Banner.Mode.OFF);
application.run(args);
@Override
public void run(String... args) throws Exception
logger.info(notify.getEnvironment());
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"ABPBatchInfrastructure.xml", "AgencyBillPayAppConfig.xml" );
JobLauncher jobLauncher = ctx.getBean(JobLauncher.class);
Job job=ctx.getBean(Job.class);
jobLauncher.run(job, new JobParametersBuilder()
.addString(documentClass,"InvoiceStatementDocumentation")
.addString(type, "2040-09-13")
.addString(emailID, notify.getSupportEmailId())
.addString(environment, notify.getEnvironment())
.toJobParameters());
ctx.close();
System.exit(0);
f
package com.abp.printbatch.config;
@Configuration
@Component
public class DBConfig
@Bean
@Primary
public DataSource dataSource()
System.out.println("");
return DataSourceBuilder.create().driverClassName("oracle.jdbc.driver.OracleDriver").url("removed")
.username("removed").password("removed").build();
【问题讨论】:
从 DBConfig 中移除 @Component 注解。将spring jpa的日志级别设置得更高。您有 2 个应用程序上下文,因为 spring boot 设置了一个,并且在创建新的 ClassPathXmlApplicationContext 时设置了另一个。 如果你使用的是Spring Boot,你不应该使用ClassPathXmlApplicationContext
; Boot 的工作是为您管理上下文。阅读入门指南,了解如何编写 CommandLineRunner
的示例。
您好 Zlaval,我已经从 DBConfig 中删除了 @Component,并且还从 ABPBatchInfrastructure.xml 中删除了组件扫描。我又得到了同样的错误。
嗨 chrylis -谨慎乐观,我添加了 ClassPathXMLApplicationContext 来实例化作业启动器。要实例化,我需要 ClassPathXMLApplicationContext 对象。如果不这样做,我将无法在实现 CommandLineRunner 接口的 FileUploadApplication.class 的 run 方法中启动 joblauncher。请让我知道是否有其他方法可以在不实例化 ClassPathXMLApplicationContext 的情况下启动作业启动器。
另外你用的是什么版本的java和jdbc驱动? “T4CConnection 没有定义或继承接口 java.sql.Connection 的已解析方法抽象 getNetworkTimeout()I 的实现。” Java 7将这两个方法添加到接口中,但是您的jdbc驱动程序似乎较旧。
【参考方案1】:
正如您所提到的,我在应用程序启动期间导入了 xml,并在 run 方法中删除了应用程序上下文初始化。我还删除了 XML 中的组件扫描。这已修复数据源未找到问题和显示 SQL 问题。现在应用程序按预期工作。下面是我的新入口点类。感谢您的所有帮助:)
@SpringBootApplication
@ComponentScan(basePackages = "com.abp.printbatch")
@ImportResource( "ABPBatchInfrastructure.xml", "AgencyBillPayAppConfig.xml" )
public class FileUploadApplication extends PrintBatchConstants implements CommandLineRunner
@Autowired
private NotifyYaml notify;
@Autowired
private ApplicationContext ctx;
final static Logger logger = LoggerFactory.getLogger(FileUploadApplication.class);
public static void main(String[] args)
SpringApplication application = new SpringApplication(FileUploadApplication.class);
application.setBannerMode(Banner.Mode.OFF);
application.run(args);
@Override
public void run(String... args) throws Exception
logger.info(notify.getEnvironment());
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"ABPBatchInfrastructure.xml", "AgencyBillPayAppConfig.xml" );
JobLauncher jobLauncher = ctx.getBean(JobLauncher.class);
Job job=ctx.getBean(Job.class);
jobLauncher.run(job, new JobParametersBuilder()
.addString(documentClass,"InvoiceStatementDocumentation") .addString(type,
"2040-09-13") .addString(emailID, notify.getSupportEmailId())
.addString(environment, notify.getEnvironment()) .toJobParameters());
ctx.close();
System.exit(0);
【讨论】:
以上是关于一个组件需要一个名为“dataSource”的 bean,但找不到该 bean的主要内容,如果未能解决你的问题,请参考以下文章
Spring Boot 1.4 @DataJpaTest - 创建名为“dataSource”的 bean 时出错
多数据源简单配置(dynamic-datasource组件+MyBatis)-快速上手系列
多数据源简单配置(dynamic-datasource组件+MyBatis)-快速上手系列