java repository模式,java spring中的注解@Repository如何工作?

I have a code like this:

Repository

@Repository

public interface EquipmentRepository extends JpaRepository{

Equipment findById(int id);

}

Service

@Service

public class EquipmentServiceImpl implements EquipmentService {

@Autowired

EquipmentRepository equipmentRepository;

@Override

public Equipment findById(int id) {

return equipmentRepository.findById(id);

}

}

I wonder that why i can call a method of 'interface EquipmentRepository'. EquipmentRepository is a interface, Right ?

解决方案

Spring Repository is responsible for importing the DAO's into the DI container and also it makes the unchecked exceptions into Spring DataAccessException. The Spring Repository annotation is meta annotated with the @Component annotation so that the repository classes will be taken up for component scanning.

Teams implementing traditional Java EE patterns such as "Data Access

Object" may also apply this stereotype to DAO classes, though care

should be taken to understand the distinction between Data Access

Object and DDD-style repositories before doing so. This annotation is

a general-purpose stereotype and individual teams may narrow their

semantics and use as appropriate.

A class thus annotated is eligible for Spring DataAccessException

translation when used in conjunction with a

PersistenceExceptionTranslationPostProcessor. The annotated class is

also clarified as to its role in the overall application architecture

for the purpose of tooling, aspects, etc.

Source: JavaDoc

but in your case you are also extending the JpaRepository of Spring Data JPA. Spring Data automatically provides implementations of common CRUD operations. The JpaRepository extends the interface CrudRepository which has the methods declared for all basic crud operations.

public interface EquipmentRepository extends JpaRepository { … }

Defining this interface serves two purposes:

First, by extending JpaRepository we get a bunch of generic CRUD

methods into our type that allows saving Equipments, deleting them and

so on.

Second, this will allow the Spring Data JPA repository infrastructure

to scan the classpath for this interface and create a Spring bean for

it.

The @EnableJpaRepositories scans all packages below com.acme.repositories for interfaces extending JpaRepository and creates a Spring bean for it that is backed by an implementation of SimpleJpaRepository (spring data provides default imlpementations of CRUD repository through this class).

So that is why even when you haven't defined the method , you are able to do crud operations through this setup.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值