Reputation: 211
@Repository
public interface MyRepository extends CrudRepository<Custom, Long> {}
@Service
@RequiredArgsConstructor
public class MyServiceImpl implements MyServiceInterface {
private final MyRepository repository;
}
I use test configuration with instructions for bean construction for testing.
How to create @Bean
for MyRepository interface
?
@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?
}
}
Upvotes: 4
Views: 9747
Reputation: 4588
Spring-boot 3.0.6
Three conditions must be met (regardeless if its for tests or for the main code):
It's not needed to have an extra "Bean declaration" for your repository interface. The @Repository and the @EnableJpaRepositories annotations are enough.
Upvotes: 0
Reputation: 1248
Just use @Autowire, spring will take care of bean creation if you had given @Repository on JPA interface.
Upvotes: 1
Reputation: 1148
If you look at the @Repository
you noticed that this annotation is a stereotype of @Component
. So when you use annotation @Repository
this class will be treat as a bean (of course, if you enable jpa repositories).
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
...
}
So if you want inject you repository into your bean, you can do like this:
@Bean
MyServiceInterface getMyService(MyRepository myRepository) {
return new MyServiceImpl(myRepository);
}
Upvotes: 0