如何修复crudepository.save(java.lang.Object)在springboot中没有访问器方法的问题?

如何修复crudepository.save(java.lang.Object)在springboot中没有访问器方法的问题?,java,spring,spring-mvc,spring-boot,spring-data,Java,Spring,Spring Mvc,Spring Boot,Spring Data,我参考了这个springboot教程,并且在我的项目中使用spring数据,我试图将数据添加到数据库中。使用下面的bt,当我尝试这样做时,我会得到一个错误,即 调用的方法公共抽象java.lang.Object org.springframework.data.repository.crudepository.save(java.lang.Object) 没有访问器方法 这是我的密码 //my controller @RequestMapping("/mode") public Str

我参考了这个
springboot
教程,并且在我的项目中使用
spring数据
,我试图将
数据添加到数据库中。使用下面的
bt,当我尝试这样做时,我会得到一个错误,即

调用的方法公共抽象java.lang.Object org.springframework.data.repository.crudepository.save(java.lang.Object) 没有访问器方法

这是我的密码

//my controller

@RequestMapping("/mode")
    public String showProducts(ModeRepository repository){
        Mode m = new Mode();
        m.setSeats(2);
        repository.save(m); //this is where the error getting from
        return "product";
    }


//implementing crud with mode repository
@Repository
public interface ModeRepository extends CrudRepository<Mode, Long> {

}

 //my mode class
@Entity
@Table(name="mode")
public class Mode implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(unique=true, nullable=false)
    private int idMode; 


    @Column(nullable=false)
    private int seats;

    //assume that there are getters and setters
}
//我的控制器
@请求映射(“/mode”)
公共字符串showProducts(ModeRepository存储库){
模式m=新模式();
m、 固定座(2);
repository.save(m);//这就是错误的来源
退回“产品”;
}
//用模式库实现crud
@存储库
公共界面现代化位置扩展CrudePository{
}
//我的模特课
@实体
@表(name=“mode”)
公共类模式实现可序列化{
私有静态最终长serialVersionUID=1L;
@身份证
@GeneratedValue(策略=GenerationType.AUTO)
@列(unique=true,nullable=false)
私有int idMode;
@列(nullable=false)
私人座位;
//假设有getter和setter
}
我是springboot的新手,有人能告诉我我做错了什么吗, 如果有人能提供一个链接让我了解
springdata

除了spring文档

之外,请更改控制器代码,以便ModerPository是一个专用的自动连接字段

    @Autowired //don't forget the setter
    private ModeRepository repository; 

    @RequestMapping("/mode")
    public String showProducts(){
        Mode m = new Mode();
        m.setSeats(2);
        repository.save(m); //this is where the error getting from
        return "product";
    }

我今天偶然发现了这个错误。IntelliJ IDEA告诉我,不鼓励直接现场注入,这在某种程度上是有意义的。您还可以在@Controller上使用构造函数注入。可能看起来像头顶,但我觉得更干净

@Controller
public class WhateverController {

    private ModeRepository repository;

    public WhateverController(ModeRepository repository) {
        this.repository = repository;
    }

    @RequestMapping("/mode")
    public String showProducts(){
        Mode m = new Mode();
        m.setSeats(2);
        repository.save(m); //this is where the error getting from
        return "product";
    }    
}

如何将存储库注入控制器?
showProducts(ModeRepository repository)
-作为方法中的一个参数,我认为它将是AutowiredOW,这实际上很好,bt为什么我不应该从
方法参数
传递
依赖项
,谢谢!通常,控制器方法参数用于将模型(解析的http请求)传递给控制器逻辑