以下以MongoRepository为例
1.基本原理
根据之前解析mybatis一样,https://www.jianshu.com/p/41b90892c9d9
推敲下来,技术层面肯定是采用的AOP技术,我们先来验证看结果
1.生成的代理对象

是一个跟SimpleMongoRepository相关的对象
2.RepositoryFactoryBeanSupport
在EnableMongoRepositories注解中默认使用了MongoRepositoryFactoryBean,
我们再来看RepositoryFactoryBeanSupport内部的实现,
RepositoryFactoryBeanSupport是一个FactoryBean,其getObject方法调用了initAndReturn方法,其内部调用了RepositoryFactorySupport的getRepository方法
3.RepositoryFactoryBeanSupport
再来看一下RepositoryFactorySupport的getRepository方法,
关键信息来了getTargetRepository方法
public T getRepository(Class repositoryInterface, Object customImplementation) {
RepositoryMetadata metadata = getRepositoryMetadata(repositoryInterface);
Class> customImplementationClass = null == customImplementation ? null : customImplementation.getClass();
RepositoryInformation information = getRepositoryInformation(metadata, customImplementationClass);
validate(information, customImplementation);
Object target = getTargetRepository(information);
// Create proxy
ProxyFactory result = new ProxyFactory();
result.setTarget(target);
result.setInterfaces(new Class[] { repositoryInterface, Repository.class });
if (TRANSACTION_PROXY_TYPE != null) {
result.addInterface(TRANSACTION_PROXY_TYPE);
}
for (RepositoryProxyPostProcessor processor : postProcessors) {
processor.postProcess(result, information);
}
if (IS_JAVA_8) {
result.addAdvice(new DefaultMethodInvokingMethodInterceptor());
}
result.addAdvice(new QueryExecutorMethodInterceptor(information, customImplementation, target));
return (T) result.getProxy(classLoader);
}
以下是MongoRepositoryFactory重写的getTargetRepository方法
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
protected Object getTargetRepository(RepositoryMetadata metadata) {
Class> repositoryInterface = metadata.getRepositoryInterface();
MongoEntityInformation, Serializable> entityInformation = getEntityInformation(metadata.getDomainType());
if (isQueryDslRepository(repositoryInterface)) {
return new QueryDslMongoRepository(entityInformation, mongoOperations);
} else {
return new SimpleMongoRepository(entityInformation, mongoOperations);
}
}
到此为止基本上对repository接口自动注册解析有一个基本的概念了,当然还没这么简单.还有一系列的注册流程,即如何把MongoRepositoryFactoryBean自动注册到sping容器里面去.
4.注册流程
注册的流程要从注解EnableMongoRepositories开始跟进分析
下图对MongoRepositoryFactoryBean相关的BeanDefinition注册做了解析
到此为止,repository接口自动注册解析基本上揭开了面纱,其中思路还是值得学习的
参考:
https://blog.csdn.net/gaolu/article/details/53415420