我是Springboot的新手,并通过Sping的“ https://spring.io/guides”指南进行学习。

现在,我尝试理解并重做本教程:"Accessing data with MySQL"

不幸的是,我在Mavenbuild期间遇到了错误:


  启动ApplicationContext时出错。要显示自动配置报告,请在启用“调试”的情况下重新运行您的应用程序。
  2017-12-07 10:26:42.708错误8100 --- [main] o.s.b.d.LoggingFailureAnalysisReporter:
  
  
  
  申请启动失败
  
  
  
  描述:
  
  xxx.controller.GoodController中的字段goodRepository需要找不到类型为'xxx.repositories.GoodRepository'的bean。
  
  行动:
  
  考虑在配置中定义类型为“ xxx.repositories.GoodRepository”的bean。
  
  流程以退出代码1完成


这是我的代码:

Good.java:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import lombok.Data;

@Entity
@Data
public class Good {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    private String name;

    public Good() {
    }

    public void setName(String name) {
        this.name = name;
    }
}


GoodRepository:

import org.springframework.data.repository.CrudRepository;

import xxx.model.Good;

public interface GoodRepository extends CrudRepository<Good, Long>
{

}


GoodController:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import xxx.model.Good;
import xxx.repositories.GoodRepository;

@Controller
@RequestMapping(path="/goods")
public class GoodController {

    @Autowired
    private GoodRepository goodRepository;

    @GetMapping(path="/add")
    public @ResponseBody String addNewGod( @RequestParam String name)
    {
        Good god= new Good();
        god.setName(name);
        goodRepository.save(god);
        return "Saved";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<Good> getAllGods()
    {
        return goodRepository.findAll();
    }

}


我的application.properties:

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/gccontest
spring.datasource.username=xxx
spring.datasource.password=xxx


该端口上存在mysql-db ...

我哪里错了?

最佳答案

您需要使用@Repository注释您的GoodRepository。
请参阅以下答案:Spring Boot Inject CrudRepository into Service

 @Repository
 public interface GoodRepository extends CrudRepository<Good, Long>{

 }

08-24 18:56