Java 通过[field]创建依赖关系[name]未满足的bean时出错
我的Spring MVC web app在运行时遇到以下未满足的依赖项错误:Java 通过[field]创建依赖关系[name]未满足的bean时出错,java,spring,spring-mvc,spring-java-config,Java,Spring,Spring Mvc,Spring Java Config,我的Spring MVC web app在运行时遇到以下未满足的依赖项错误: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'taskConfig': Unsatisfied dependency expressed through field 'dataSource'; nested exception is org.springframework
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'taskConfig': Unsatisfied dependency expressed through field 'dataSource';
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in com.myapps.todolist.main.DataSourceConfig: Bean instantiation via factory method failed;
TaskConfig
是一个JavaConfig类,它依赖于dataSource
(类型为DriverManager dataSource
),该类在单独的JavaConfig类DataSourceConfig
中配置
TaskConfig.java
package com.myapps.todolist.main;
@Configuration
public class TaskConfig {
@Autowired
private DataSource dataSource;
@Bean
public TaskEntityDao taskEntityDao()
{
TaskEntityDao taskEntityDao = new TaskEntityDaoImpl();
taskEntityDao.setDataSource(this.dataSource);
return taskEntityDao;
}
}
package com.myapps.todolist.main;
@Configuration
public class DataSourceConfig {
@Bean
public DataSource dataSource()
{
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/MyTable");
dataSource.setUsername("username");
dataSource.setPassword("password");
return dataSource;
}
}
DataSourceConfig.java
package com.myapps.todolist.main;
@Configuration
public class TaskConfig {
@Autowired
private DataSource dataSource;
@Bean
public TaskEntityDao taskEntityDao()
{
TaskEntityDao taskEntityDao = new TaskEntityDaoImpl();
taskEntityDao.setDataSource(this.dataSource);
return taskEntityDao;
}
}
package com.myapps.todolist.main;
@Configuration
public class DataSourceConfig {
@Bean
public DataSource dataSource()
{
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/MyTable");
dataSource.setUsername("username");
dataSource.setPassword("password");
return dataSource;
}
}
为什么TaskConfig无法找到数据源
对象
我的Spring配置包括以下内容,用于扫描这两个类所在包中的JavaConfig:
<context:component-scan base-package="com.myapps.todolist.main" />
你能上传完整的错误标记吗?我想你必须将
DataSourceConfig
中的@Bean
注释从方法头移到类头。@Afridi我觉得有点傻,因为我没有正确地查看堆栈跟踪。但是我已经从中添加了一些更多的信息-似乎是找不到DriverManagerDataSource
类的问题。@peteholl是的,由于缺少类定义,在创建名为“dataSource”的bean时会发生此异常。因此,请检查所需的maven依赖项。除此之外,一切正常。第一个例外:您需要将DataSourceConfig
导入TaskConfig
以引用bean。您可以执行类似于公共任务EntityDao任务EntityDao(数据源ds)
的操作。第二个例外:它是NoClassDefFoundError,您使用的是哪个版本的Spring?