简体   繁体   中英

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?
 }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM