How to create bean for spring data jpa repository?

Viewed 2183
@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?
 }
}
2 Answers

Just use @Autowire, spring will take care of bean creation if you had given @Repository on JPA class.

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); 
 }
Related