![](/img/trans.png)
[英]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.