spring data jpa原理浅析

       当我们把一个标准的spring data jpa的repository注入到其它spring bean中时,会发现该repository实际上是由

JdkDynamicAopProxy生成的一个代理类(org.springframework.data.jpa.repository.support.SimpleJpaRepository@5748638c)。查看SimpleJpaRepository源码会发现SimpleJpaRepository中有CrudRepository接口所有方法的实现。当我们调用CrudRepository中的方法时,实际上是调用SimpleJpaRepository中对应的方法。而我们在repository中自定义方法则是通过在生成代理类的同时,添加的MethodInterceptor实现。

源码分析:

以@Resource注入bean为例,最终实现注入的是org.springframework.context.annotation.CommonAnnotationBeanPostProcessor。spring容器在启动时,会从bean容器中获取相应的bean注入。单例bean的获取会调用org.springframework.beans.factory.support.DefaultSingletonBeanRegistry中

getSingleton(String beanName, ObjectFactory<?> singletonFactory)方法,具体获取bean的代码是
singletonObject = singletonFactory.getObject(),可以看出是通过该方法第二个参数中的方法获取的,而ObjectFactory是一个接口,

该接口中只有一个方法

T getObject() throws BeansException,通过调用栈发现,调用getSingleton方法的是org.springframework.beans.factory.support.AbstractBeanFactory中的doGetBean方法,具体代码如下:

if (mbd.isSingleton()) {
   sharedInstance = getSingleton(beanName, () -> {
      try {
         return createBean(beanName, mbd, args);
      }
      catch (BeansException ex) {
         // Explicitly remove instance from singleton cache: It might have been put there
         // eagerly by the creation process, to allow for circular reference resolution.
         // Also remove any beans that received a temporary reference to the bean.
         destroySingleton(beanName);
         throw ex;
      }
   });
   bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}

发现传入的ObjectFactory是一个lambda表达式,这就是spring创建单例bean调用的方法。spring在实例化bean对象之后会初始化bean,初始化时,如果bean实现了InitializingBean接口,会调用InitializingBean的afterPropertiesSet()方法。而repository在这一步创建的bean就实现了该接口https://blog.csdn.net/sinat_33472737/article/details/105838278。最终会调用org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport中的afterPropertiesSet方法。该发放会初始化一些成员变量,我们所关心的是

this.repository = Lazy.of(() -> this.factory.getRepository(repositoryInterface, repositoryFragmentsToUse));接着往下看,factory.getRepository调用的是org.springframework.data.repository.core.support.RepositoryFactorySupport中的getRepository方法。
result.addAdvice(new QueryExecutorMethodInterceptor(information, projectionFactory));该行代码就是给我们在repository中自定义的根据方法名生成对应sql的通知拦截器
T repository = (T) result.getProxy(classLoader);该行代码就是生成代理repository的。调试发现该方法最终返回的就是SimpleJpaRepository代理类

猜你喜欢

转载自blog.csdn.net/sinat_33472737/article/details/104904535