繁体   English   中英

无法创建 JPA/CRUDRepository bean

[英]Unable to create JPA/CRUDRepository bean

我正在使用 Spring 数据 JPA 创建首次 spring rest 服务。

并低于错误。


应用程序启动失败


描述:

com.example.demo.controller.AddProduct 中的字段 product_repo 需要找不到类型为“com.example.demo.repository.ProductRepositroy”的 bean。

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

行动:

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

我的class和接口是:

  1. Controller
@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 中注册这个class。

代码应该是这样的。

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

}

快乐编码: :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM