java 如何为spring data jpa仓库创建bean?

ryoqjall  于 2023-01-29  发布在  Java
关注(0)|答案(2)|浏览(140)
@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?
 }
}
llmtgqce

llmtgqce1#

只要使用@Autowire,如果您在JPA接口上提供了@Repository,spring将负责bean的创建。

1l5u6lss

1l5u6lss2#

如果你查看@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); 
 }

相关问题