Ilja Tarasovs
Ilja Tarasovs

Reputation: 211

How to create bean for spring data jpa repository?

@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

Answers (3)

Heri
Heri

Reputation: 4588

Spring-boot 3.0.6

Three conditions must be met (regardeless if its for tests or for the main code):

  1. The repository must have the @Repository annotation
  2. The class that uses the autowired member or constructor param must be a spring bean
  3. JpaRepositories must be enabled (annotate "@EnableJpaRepositories(basePackages = "com.example.app")" somewhere in your configuration class)

It's not needed to have an extra "Bean declaration" for your repository interface. The @Repository and the @EnableJpaRepositories annotations are enough.

Upvotes: 0

Alpit Anand
Alpit Anand

Reputation: 1248

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

Upvotes: 1

Mateusz Korwel
Mateusz Korwel

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

Related Questions