[英]Spring JPA Data Repository failed to create bean for interface that extends CrudRepository
[英]How to create bean for spring data jpa repository?
@Repository
public interface MyRepository extends CrudRepository<Custom, Long> {}
@Service
@RequiredArgsConstructor
public class MyServiceImpl implements MyServiceInterface {
private final MyRepository repository;
}
我使用測試配置和 bean 構造說明進行測試。
如何為MyRepository interface
創建@Bean
?
@TestConfiguration
@EnableJpaRepositories(basePackages = "com.example.app")
public class TestBeans {
@Bean
MyServiceInterface getMyService() {
return new MyServiceImpl(getMyRepository());
}
@Bean
MyRepository getMyRepository() {
return null; // what should be here?
}
}
只需使用@Autowire,如果您在 JPA class 上提供了@Repository,則 spring 將負責創建 bean。
如果您查看@Repository
,您會注意到此注釋是@Component
的原型。 因此,當您使用注釋@Repository
時,此 class 將被視為 bean(當然,如果您啟用 jpa 存儲庫)。
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
...
}
因此,如果您想將存儲庫注入到您的 bean 中,您可以這樣做:
@Bean
MyServiceInterface getMyService(MyRepository myRepository) {
return new MyServiceImpl(myRepository);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.