我犯了一个非常愚蠢的错误,但无法找出解决方法。
我有一个使用配置文件的简单SpringBoot应用程序,该配置文件连接到MongoDb。
我的pom.xml依赖项:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
我的StudentController.java
@RestController
@RequestMapping("/students")
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping(method = RequestMethod.GET)
public Collection<Student> getAllStudents(){
return studentService.getAllStudents();
}
}
我的StudentService.java
@Service
public class StudentService {
@Autowired
private StudentDao studentDao;
public Collection<Student> getAllStudents(){
return this.studentDao.getAllStudents();
}
}
我的StudentDao.java接口:
public interface StudentDao {
Collection<Student> getAllStudents();
}
我的MongoStudentDaoImpl.java:
@Repository
@Profile("test")
public class MongoStudentDaoImpl implements StudentDao {
@Autowired
private MongoStudentRepo repo;
@Override
public Collection<Student> getAllStudents() {
return repo.findAll();
}
}
我的MongoStudentRepo.java:
@Profile("test")
public interface MongoStudentRepo extends MongoRepository<Student, String> {
}
当我尝试使用“测试”配置文件启动应用程序时,这是我看到的错误:
上下文初始化期间遇到异常-取消
刷新尝试:
org.springframework.beans.factory.UnsatisfiedDependencyException:
创建名称为'studentController'的bean时出错:不满意
通过字段“ studentService”表示的依赖关系;嵌套异常
是org.springframework.beans.factory.UnsatisfiedDependencyException:
创建名称为'studentService'的bean时出错:不满意的依赖关系
通过字段“ studentDao”表示;嵌套异常为
org.springframework.beans.factory.UnsatisfiedDependencyException:
创建名称为'mongoStudentDaoImpl'的bean时出错:不满意
通过字段“ repo”表示的依赖关系;嵌套异常为
org.springframework.beans.factory.NoSuchBeanDefinitionException:否
可用类型为“ MongoStudentRepo”的合格Bean:
期望至少有1个符合自动装配候选条件的bean。
依赖注释:
{@ org.springframework.beans.factory.annotation.Autowired(required = true)}
我在这里想念什么?我是否需要在
MongoStudentRepo.java
中添加注释?提前致谢。
最佳答案
您的接口类不需要注释,因为Spring Data存储库接口由Spring Data专门处理。
最可能的情况是您的存储库类没有被Spring Data标识(您未指定Spring Boot版本或软件包名称),在这种情况下,您可能需要在@EnableMongoRepositories
类上使用@Configuration
(您的Spring引导启动器类也是其中之一)。