【发布时间】:2019-08-27 09:07:10
【问题描述】:
编辑添加 proc 结构:
主/java 你好(包) 应用程序(主应用程序) 测试休息控制器 型号(包) 测试 服务(包) TestRepo(接口)
我目前正在查看组件扫描,因为刚刚发布了异常中的“repo.Test”是一个线索。
我已经阅读了许多教程和问题,但仍然无法找到我特定问题的答案,这很可能是由于我缺乏理解。
我有一个要添加数据库的 Spring Boot 应用程序。我一直在关注本教程:https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/
但是,当我尝试运行我的应用程序(按照相同的步骤)时,我得到了一个异常:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'testRestController': Unsatisfied dependency expressed through field 'testRepo'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'repo.TestRepo' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
我确实有另一个自动装配的 bean,主要区别在于这个 bean(工作的那个)有一个实现接口的服务和一个 bean 配置类。 JPA 的示例都没有遵循该模型,创建一个服务来重新实现 JPARepo 中的方法似乎很愚蠢。
这是我正在使用的控制器:
@RestController
public class TestRestController {
@Autowired
GreetingService greetingService;
@Autowired
TestRepo testRepo;
@RequestMapping("/hello")
public String home() {
return greetingService.greet();
}
@RequestMapping("/testrepo")
public String testrepo() {
Test test = new Test("steve");
testRepo.save(test);
Long idOftest = test.getId();
test = null;
test = testRepo.findById(idOftest).get();
return "DID THIS WORK::::: + "+ test.toString();
}
界面是
@Repository
public interface TestRepo extends JpaRepository<Test, Long> {
}
和模型:
@Entity
@Data
public class Test {
private final String name;
public Test(String name){
this.name = name;
}
@Id
@GeneratedValue
private Long id;
public Long getId(){
return this.id;
}
}
应用程序主要是:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
// @Bean
// public CommandLineRunner commandLineRunner(ApplicationContext ctx ) {
// return args -> {
//
// System.out.println("Let's inspect the beans provided by Spring Boot:");
//
// String[] beanNames = ctx.getBeanDefinitionNames();
// Arrays.sort(beanNames);
// for (String beanName : beanNames) {
// System.out.println(beanName);
// }
//
//
// };
// }
}
我最近注释掉了 bean 注释,看看这是否会导致问题。
提前感谢您的帮助!
【问题讨论】:
-
你能发布你的项目结构吗?具体来说,包三中的文件
TestRepo类和主类(包含main方法的那个)位于哪里? -
请贴出你的项目的包结构
-
查看这个答案,它解决了完全相同的问题stackoverflow.com/questions/52154652/…
标签: java spring-boot spring-mvc jpa autowired