【发布时间】:2018-06-05 12:25:03
【问题描述】:
我正在尝试在 Spring Boot 应用程序中使用 Spring 数据和存储库,但在编译项目时出现错误。
这是我的实体:
package fr.investstore.model;
import javax.persistence.Id;
...
@Entity
public class CrowdOperation {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public Long id;
@Enumerated(EnumType.STRING)
public RepaymentType repaymentType;
...
}
以及对应的Repository:
package fr.investstore.repositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import fr.investstore.model.CrowdOperation;
public interface CrowdOperationRepository extends CrudRepository<CrowdOperation, Long> {
}
我在一个WS控制器中使用它,通过Autowired注解生成一个仓库:
package fr.investstore.ws;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
...
@Controller
@EnableAutoConfiguration
public class SampleController {
@Autowired
private CrowdOperationRepository crowdOperationRepository;
@RequestMapping(path = "/", method = RequestMethod.GET)
@ResponseBody
public String getOperations(@RequestParam(required=true, defaultValue="Stranger") String name) {
crowdOperationRepository.save(new CrowdOperation());
return "Hello " + name;
}
}
以及应用程序的代码:
package fr.investstore;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import fr.investstore.ws.SampleController;
@SpringBootApplication
public class InvestStoreApplication {
public static void main(String[] args) {
SpringApplication.run(SampleController.class, args);
}
}
但是在编译项目时我得到:
应用程序启动失败
描述:字段 crowdOperationRepository 在 fr.investstore.ws.SampleController 需要一个 bean 类型 'fr.investstore.repositories.CrowdOperationRepository' 不能 找到了。
操作:考虑定义一个 bean 类型 'fr.investstore.repositories.CrowdOperationRepository' 在您的 配置。
Spring不会通过接口自动为repository生成一个bean吗? 我该如何解决这个问题?
编辑:我还尝试将Repository 注释(来自org.springframework.stereotype.Repository)放到CrowdOperationRepository 上,但我得到了同样的错误
【问题讨论】:
-
1.这是运行时错误,而不是编译错误。 2. 发布您的 Application 类的代码,包括包声明。
-
@JBNizet 我已经更新了帖子来放 App 类的代码
-
将
SpringApplication.run(SampleController.class, args);替换为SpringApplication.run(InvestStoreApplication.class, args);。并删除控制器上无用的@EnableAutoConfiguration。 -
你需要同时做这两件事,Ravat Tailor 和 SeverityOne 在那里写的答案!
-
@JBNizet 你能添加一个答案吗?我会接受它,因为它工作得很好:)
标签: spring hibernate repository spring-data-jpa spring-repositories