我正在尝试在 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 Controller 中使用它,通过 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);
}
}
但是在编译项目时我得到:
APPLICATION FAILED TO START
Description: Field crowdOperationRepository in fr.investstore.ws.SampleController required a bean of type 'fr.investstore.repositories.CrowdOperationRepository' that could not be found.
Action: Consider defining a bean of type 'fr.investstore.repositories.CrowdOperationRepository' in your configuration.
Spring不会通过接口(interface)自动为repository生成一个bean吗? 我该如何解决这个问题?
编辑:我还尝试将 Repository
注释(来自 org.springframework.stereotype.Repository
)放到 CrowdOperationRepository
上,但我得到了同样的错误
最佳答案
在创建 spring-boot 应用程序时,我们需要记住一些要点,例如
始终将主类(带有 `@SpringBootApplication 注释的类)放在顶层包中,其他类应位于子包下。
始终使用适当的注释标记您的 bean 类,例如所有的repository都用
@Repository
注解,所有的服务实现类都用@Service
注解,其他组件类用@Component
注解>,定义我们 bean 的类应该标记为@Configuration
启用您正在使用的功能,例如
@EnableJpaRepositories
、@EnableTransactionManagement
、@EnableJpaAuditing
,这些注解还提供了让我们定义spring需要扫描哪个包的功能。
因此,在您的情况下,您需要使用 @EnableJpaRepositories
注释标记 InvestStoreApplication
类,使用 @Repository
标记 CrowdOperationRepository
>.
关于编译时找不到 Spring 数据存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47948450/