@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?
}
}
2条答案
按热度按时间llmtgqce1#
只要使用@Autowire,如果您在JPA接口上提供了@Repository,spring将负责bean的创建。
1l5u6lss2#
如果你查看
@Repository
,你会发现这个注解是@Component
的原型,所以当你使用注解@Repository
时,这个类会被当作bean(当然,如果你启用了jpa存储库的话)。所以如果你想把你的存储库注入到你的bean中,你可以这样做: