Spring Data autowire the repository interfaces dir

2019-07-15 03:25发布

I am new to Spring Data and I would like to know if it is correct to autowire the repositories direcly this way (supposing no more methods are needed) since Spring 4 can solve generic autowiring:

@Autowired
CrudRepository<User,Long> repo;

There is more than one bean that implements this interface (SimpleJPARepository, QueryDslJpaRepository) so Spring couldn't solve the autowiring isn't it?

But when if you do:

public interface MyRepo extends CrudRepository<User,Long> () {
}

What bean autowire for the implementation?

Thanks.

1条回答
Viruses.
2楼-- · 2019-07-15 03:44

I don't know if you can autowire CrudRepository<User,Long> repo; directly, I guess that could work. Try it.

Usually you declare that you want to have a repository for User by defining an interface like

public interface MyRepo extends CrudRepository<User,Long> () {
}

and then you simply autowire it. (I would also suggest you name it UserRespository because that's what it's job is)

@Autowired
MyRepo repo;

The magic trick is that Spring Data then implements the interface for you. You get that implementation autowired and your code stays clean of implementation details of the database you use.

There is more than one bean that implements this interface (SimpleJPARepository, QueryDslJpaRepository) so Spring couldn't solve the autowiring isn't it?

It has to do that in the regular case as well. There are rules & configuration somewhere that will decide which implementation to pick in case it has more than 1 candidate for the interface you want.

In case of SimpleJPARepository vs QueryDslJpaRepository it probably boils down to whether you use the extra features or not. The documentation of the latter is

QueryDsl specific extension of SimpleJpaRepository which adds implementation for QueryDslPredicateExecutor.

If you don't want a type that inherits QueryDslPredicateExecutor it doesn't need to base the magic implementation on that class.

查看更多
登录 后发表回答