如何为Spring Data JPA Repository创建bean?

3
@Repository
public interface MyRepository extends CrudRepository<Custom, Long> {}

@Service
@RequiredArgsConstructor
public class MyServiceImpl implements MyServiceInterface {
 
 private final MyRepository repository;
}

我使用测试配置和有关bean构建的说明进行测试。
如何为MyRepository接口创建@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?
 }
}

1
我觉得你可以直接使用自动装配来注入这个仓库,不是吗? - undefined
也在考虑这个。或许还有其他解决方案吗? - undefined
1
@IljaTarasovs 这是唯一正确的方法。为什么你需要另外一个解决方案呢? - undefined
是的,我同意你们所有人的观点。我会使用@Autowired - undefined
3个回答

1

只需使用 @Autowire,如果您在 JPA 接口上标注了 @Repository,Spring 将负责创建 bean。


同意你的评论 - undefined

0

如果您查看@Repository,您会注意到此注释是@Component的一种类型。因此,当您使用注释@Repository时,此类将被视为bean(当然,如果您启用jpa存储库)。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
   ...
}

如果你想将仓库注入到你的Bean中,可以这样做:

 @Bean 
 MyServiceInterface getMyService(MyRepository myRepository) {
  return new MyServiceImpl(myRepository); 
 }

0

Spring-boot 3.0.6

无论是用于测试还是主要代码,必须满足以下三个条件:

  1. 存储库必须具有@Repository注解
  2. 使用@Autowired成员或构造函数参数的类必须是Spring Bean
  3. JpaRepositories必须启用(在配置类中的某个地方注释"@EnableJpaRepositories(basePackages = "com.example.app")")

您的存储库接口不需要额外的"Bean声明"。@Repository和@EnableJpaRepositories注解就足够了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接