您的位置:首页 > 编程语言 > Java开发

Spring Data中手动实现Repository方法

2015-09-09 19:50 447 查看
Spring Data中Repository或者其子接口各种类型的操作都是由Spring Data的基础设施实现的,要么通过背后的实

现类,要么就是通过查询执行引擎。当构建应用程序的时候,这两种场景可能会覆盖你大部分数据访问操作。但是,但

某些场景下你可能需要手动实现代码。在Spring Data中,手动实现操作需要在类中遵循一定的命名规范。

package com.silence.springdata.custom;

interface CustomRepositoryCustom {

Person customMethod();

}

package com.silence.springdata.custom;

class CustomRepositoryImpl implements CustomRepositoryCustom {

@Override

public Person customMethod() {

//自定义方法代码

return null;

}

}

接口和实现类均不需要了解Spring Data的任何事情。它与使用Spring手动实现代码非常类似。按照Spring Data来

看,这个代码片段最有意思的地方在于实现类的名字遵循了命名规范,也就是核心Repository接口(例如在上面我们

的例子中CustomRepository )的名字上加上Impl后缀。同时需要注意的是。我们将接口和实现类都设置为包内私有,

从而阻止从包外访问它们。最后一步是修给Repository接口的声明,使其扩展刚刚引入的接口。

package com.silence.springdata.custom;

import org.springframework.data.repository.CrudRepository;

public interface CustomRepository extends CrudRepository<Person, Integer>,CustomRepositoryCustom {

//..................

}

现在,我们已经将CustomRepository暴露的API引入到CustomRepositoryTest中心点。客户端代码现在

就可以调用CustomRepositoryTest.customMethod()方法了。但是,这个实现类会如何被发现并至于最终执行的代理

之中呢?实际上,Respository的启动过程看起来是这样子的。

1.发现repository接口。(如CustomRepository)

2.尝试寻找一个Bean定义,这个Bean的名字为接口的小写形式并添加Impl后缀(如CumtomRepositoryImpl),若找到,就使用它。

3.如果没有找到,我们会扫描寻找一个类,这个类的名字为核心Repository接口的名字并添加Impl后缀。

4.找到的自定义实现类将会自动装配到被发现接口的代理配置中并且在方法调用时作为潜在的目标类。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: