无法创建JPA/CRUDRepository bean



我正在使用spring Data JPA创建首次spring-rest服务。

并低于错误。


应用程序无法启动


描述:

com.example.demo.controller.AddProduct中的字段product_repo需要一个类型为"com.example.demo.repository.ProductRepositroy"的bean,但找不到该bean。

注入点具有以下注释:-@org.springframework.beans.factory.annotation.Autowired(required=true(

行动:

考虑在您的配置中定义一个类型为"com.example.demo.repository.ProductRepositroy"的bean。

我的类和接口是:

  1. 控制器
@RestController
public class AddProduct {


@Autowired
private ProductRepositroy product_repo;

@GetMapping("/add")
public String addproduct() {


Product p1 = new Product();
p1.setId(1);
p1.setName("Amit");


Product p2 = new Product();
p1.setId(2);
p1.setName("Sumit");


product_repo.save(p1);
product_repo.save(p2);


return "added successfully the recod";

}
}
  1. 实体
@Entity
public class Product {

@Id
private int id;
private String name;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}
  1. 存储库
public interface ProductRepositroy extends CrudRepository<Product, Integer> {
}
  1. 应用程序测试
@SpringBootApplication
public class Demo1Application {
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
}


}

在ProductRepositroy接口上添加@Repository注释。也不是扩展CrudRepository,而是扩展JpaRepository。

您应该在存储库中使用@Repository在bean中注册此类。

代码应该是这样的。

@Repository
public interface ProductRepositroy extends CrudRepository<Product, Integer> {
}

快乐编码!:(

最新更新