我正在尝试在 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;
...
}
以及相应的存储库:
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> {
}
Autowired
我在 WS 控制器中使用它,通过注解生成存储库:
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);
}
}
但是在编译项目时,我得到:
应用程序无法启动
说明:fr.investstore.ws.SampleController 中的字段 crowdOperationRepository 需要找不到类型为“fr.investstore.repositories.CrowdOperationRepository”的 bean。
行动:考虑在您的配置中定义“fr.investstore.repositories.CrowdOperationRepository”类型的 bean。
Spring不会通过接口自动为存储库生成一个bean吗?我该如何解决这个问题?
编辑:我也尝试将Repository
注释(从org.springframework.stereotype.Repository
)放到 上CrowdOperationRepository
,但我得到了同样的错误