主頁 > 後端開發 > 原始碼決議Spring AOP的加載與生效

原始碼決議Spring AOP的加載與生效

2021-09-06 06:27:33 後端開發

  本次博主主要進行Spring AOP這里的決議,因為在作業中使用后,卻不知道背后的實作原理并在使用的程序中發現了一些認知缺陷,所以決定寫這么一篇文章以供大家參考參考,進入正題,

  本次博主使用了@Aspect、@Around、@PointCut注解實作了一些小的需求,大家想必都用過,我就簡單的舉個例子吧,

  1 @Aspect
  2 @Component
  3 public class CrmCacheAspect {
  4 
  5     @Autowired
  6     StringRedisTemplate stringRedisTemplate;
  7 
  8     private ConcurrentHashMap<String, ICacheResultParser> parserMap = new ConcurrentHashMap();
  9 
 10     private ConcurrentHashMap<String, IKeyGenerator> generatorMap = new ConcurrentHashMap();
 11 
 12     private ConcurrentHashMap<String,Boolean> keyMap = new ConcurrentHashMap<>();
 13     @Pointcut("@annotation(com.bjh.hms.crm.annotation.CrmCache)")
 14     public void pointCut(){}
 15 
 16     @Around("pointCut() && @annotation(crmCache)")
 17     public Object joinPoint(ProceedingJoinPoint joinPoint, CrmCache crmCache) throws InstantiationException, IllegalAccessException {
 18         String valuehttps://www.cnblogs.com/guoxiaoyu/p/= "";
 19         String key = "";
 20         Object result = "";
 21         try {
 22             key = getKey(crmCache,joinPoint);
 23             value =https://www.cnblogs.com/guoxiaoyu/p/ stringRedisTemplate.opsForValue().get(key);
 24         } catch (Exception e) {
 25             XxlJobHelper.log("獲取快取{}失敗:{}",crmCache.key(),e);
 26         } finally {
 27             if (StringUtils.isBlank(value)) {
 28                 value =https://www.cnblogs.com/guoxiaoyu/p/ synchronizeCache(key, joinPoint, crmCache);
 29             }
 30             result = getResult(crmCache, value, joinPoint);
 31         }
 32         return result;
 33     }
 34 
 35     private Object getResult(CrmCache crmCache,
 36                              String value,
 37                              ProceedingJoinPoint joinPoint) throws InstantiationException, IllegalAccessException {
 38         if (value =https://www.cnblogs.com/guoxiaoyu/p/= null) {
 39             return null;
 40         }
 41         String name = crmCache.parser().getName();
 42         ICacheResultParser iCacheResultParser;
 43         if (parserMap.containsKey(name)) {
 44             iCacheResultParser = parserMap.get(name);
 45         } else {
 46             iCacheResultParser = crmCache.parser().newInstance();
 47             parserMap.put(name,iCacheResultParser);
 48         }
 49         MethodSignature signature = (MethodSignature) joinPoint.getSignature();
 50         Class returnType = signature.getReturnType();
 51         Object parse = iCacheResultParser.parse(value, returnType);
 52         return parse;
 53     }
 54 
 55     /**
 56      * Title: 解決redis并發穿透
 57      * @author 2021/8/13 17:15
 58      * @return java.lang.String
 59      */
 60     private String synchronizeCache(String key,
 61                                     ProceedingJoinPoint joinPoint,
 62                                     CrmCache crmCache) {
 63         String valuehttps://www.cnblogs.com/guoxiaoyu/p/= "";
 64         //暫停100-200ms,執行緒順序執行
 65         try {
 66             Thread.sleep((int)(Math.random()*(200 - 100 + 1) + 100));
 67         } catch (InterruptedException e) {
 68             XxlJobHelper.log("synchronizeCache error {}", ExceptionUtil.stacktraceToString(e));
 69         }
 70         while (StringUtils.isBlank(value =https://www.cnblogs.com/guoxiaoyu/p/ stringRedisTemplate.opsForValue().get(key))
 71         && (keyMap.get(key) == null || keyMap.get(key))){
 72             //防止重復呼叫
 73             if (keyMap.get(key) == null || !keyMap.get(key)) {
 74                 keyMap.put(key,true);
 75                 Object proceed = null;
 76                 try {
 77                     proceed = joinPoint.proceed();
 78                 } catch (Throwable e) {
 79                     XxlJobHelper.log("處理失敗:{}",ExceptionUtil.stacktraceToString(e));
 80                 }
 81                 putValueByRedis(key,proceed,crmCache);
 82                 keyMap.put(key,false);
 83             }
 84         }
 85         keyMap.remove(key);
 86         return value;
 87     }
 88 
 89     private void putValueByRedis(String key, Object value, CrmCache crmCache) {
 90         if (value =https://www.cnblogs.com/guoxiaoyu/p/= null) {
 91             return;
 92         }
 93         if (value instanceof String) {
 94             stringRedisTemplate.opsForValue().set(key, value.toString());
 95         } else {
 96             String jsonString = JSONObject.toJSONString(value);
 97             stringRedisTemplate.opsForValue().set(key,jsonString);
 98         }
 99         //-1代表不過期
100         if (crmCache.expire() != -1) {
101             stringRedisTemplate.expire(key, crmCache.expire(), TimeUnit.MINUTES);
102         }
103     }
104 
105     private String getKey(CrmCache crmCache, ProceedingJoinPoint joinPoint) throws InstantiationException, IllegalAccessException {
106         MethodSignature signature = (MethodSignature) joinPoint.getSignature();
107         Method method = signature.getMethod();
108         Object[] args = joinPoint.getArgs();
109         String iKeyGeneratorName = crmCache.generator().getName();
110         String key = crmCache.key();
111         IKeyGenerator iKeyGenerator = null;
112         if (generatorMap.containsKey(iKeyGeneratorName)) {
113             iKeyGenerator = generatorMap.get(iKeyGeneratorName);
114         } else {
115             iKeyGenerator = crmCache.generator().newInstance();
116             generatorMap.put(iKeyGeneratorName,iKeyGenerator);
117         }
118         return iKeyGenerator.generate(key,method,args);
119     }
120 
121 }

  本例子主要是對結果與請求進行決議快取,spring其實有自帶的,但是不可以使用快取時間,有快取時間又需要引入其他依賴包,公司內部私服又是內網訪問的,所以就自寫了一個簡單的注解實作了快取有限時間功能,這不是重點,我們來分析一下注解是如何加載進來的,又是如何被spring走進來決議的吧,

  講解之前,博主還是一如既往的為大家畫了幾張草圖,以便大家防止看代碼看暈,先來第一張:aspect注解原始碼分析加載與生效

  https://www.processon.com/view/link/6134aae163768906a2203894

  我們開始走代碼,我們直接走bean的創建開始,如果有小伙伴不知道整個bean創建流程的話,可以看一下博主以前的畫 的草圖腦補一下:

  https://www.processon.com/view/link/5f704050f346fb166d0f3e3c

  代碼走起,任意的bean創建都可以,如果看不了靜態代碼,自行debug就可以了,

 1     protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
 2         Object bean = null;
 3         if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
 4             // 確定是否有aspect注解
 5             if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
 6                 Class<?> targetType = determineTargetType(beanName, mbd);
 7                 if (targetType != null) {
 8                     //決議注解
 9                     bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
10                     if (bean != null) {
11                         //此處會給有自定義注解的bean創建代理類回傳
12                         bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
13                     }
14                 }
15             }
16             mbd.beforeInstantiationResolved = (bean != null);
17         }
18         return bean;
19     }

  我們分析一下hasInstantiationAwareBeanPostProcessors方法,看看是如何走進來的,從方法名字可以看出,是否有InstantiationAwareBeanPostProcessors后置處理器,那我們本身并沒有去填加這個類,那怎么就有了呢,原因就在我們引入aop包依賴后,有一個默認的自動配置AopAutoConfiguration,EnableAspectJAutoProxy注解中間引入了一個AspectJAutoProxyRegistrar類,實作這個registerBeanDefinitions方法后,引入了一個AnnotationAwareAspectJAutoProxyCreator類,這個類就是AspectJAutoProxyRegistrar的實作類,所以hasInstantiationAwareBeanPostProcessors方法走通了,

  再看一下applyBeanPostProcessorsBeforeInstantiation方法決議注解流程,

 

 1 public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
 2         Object cacheKey = getCacheKey(beanClass, beanName);
 3 
 4         if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
 5             if (this.advisedBeans.containsKey(cacheKey)) {
 6                 return null;
 7             }//我們主要分析一下shouldSkip方法
 8             if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
 9                 this.advisedBeans.put(cacheKey, Boolean.FALSE);
10                 return null;
11             }
12         }
13 
14         // Create proxy here if we have a custom TargetSource.
15         // Suppresses unnecessary default instantiation of the target bean:
16         // The TargetSource will handle target instances in a custom fashion.
17         TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
18         if (targetSource != null) {
19             if (StringUtils.hasLength(beanName)) {
20                 this.targetSourcedBeans.add(beanName);
21             }
22             Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
23             Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
24             this.proxyTypes.put(cacheKey, proxy.getClass());
25             return proxy;
26         }
27 
28         return null;
29     }
 1     protected boolean shouldSkip(Class<?> beanClass, String beanName) {
 2         // TODO: Consider optimization by caching the list of the aspect names
 3         //主要這里獲取了注解
 4         List<Advisor> candidateAdvisors = findCandidateAdvisors();
 5         for (Advisor advisor : candidateAdvisors) {
 6             if (advisor instanceof AspectJPointcutAdvisor &&
 7                     ((AspectJPointcutAdvisor) advisor).getAspectName().equals(beanName)) {
 8                 return true;
 9             }
10         }
11         return super.shouldSkip(beanClass, beanName);
12     }
 1     //此方法分為兩步
 2     protected List<Advisor> findCandidateAdvisors() {
 3         // Add all the Spring advisors found according to superclass rules.
 4         //第一步從bean工廠中找到所有Advisor的實作類
 5         List<Advisor> advisors = super.findCandidateAdvisors();
 6         // Build Advisors for all AspectJ aspects in the bean factory.
 7         if (this.aspectJAdvisorsBuilder != null) {
 8         //主要是第二步:從bean工廠中找到所有帶有@aspect注解的類
 9             advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
10         }
11         return advisors;
12     }

  我們直接看第二步即可

 

 1     public List<Advisor> buildAspectJAdvisors() {
 2         List<String> aspectNames = this.aspectBeanNames;
 3 
 4         if (aspectNames == null) {
 5             synchronized (this) {
 6                 aspectNames = this.aspectBeanNames;
 7                 if (aspectNames == null) {
 8                     List<Advisor> advisors = new ArrayList<>();
 9                     aspectNames = new ArrayList<>();
10                     //獲取所有類
11                     String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
12                             this.beanFactory, Object.class, true, false);
13                     for (String beanName : beanNames) {
14                         if (!isEligibleBean(beanName)) {
15                             continue;
16                         }
17                         // We must be careful not to instantiate beans eagerly as in this case they
18                         // would be cached by the Spring container but would not have been weaved.
19                         Class<?> beanType = this.beanFactory.getType(beanName);
20                         if (beanType == null) {
21                             continue;
22                         }
23                         //改類是否是我們寫的aspect注解類
24                         if (this.advisorFactory.isAspect(beanType)) {
25                             aspectNames.add(beanName);
26                             AspectMetadata amd = new AspectMetadata(beanType, beanName);
27                             if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
28                                 MetadataAwareAspectInstanceFactory factory =
29                                         new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
30                                 //開始在這里決議
31                                 List<Advisor> classAdvisors = this.advisorFactory.getAdvisors(factory);
32                                 if (this.beanFactory.isSingleton(beanName)) {
33                                     this.advisorsCache.put(beanName, classAdvisors);
34                                 }
35                                 else {
36                                     this.aspectFactoryCache.put(beanName, factory);
37                                 }
38                                 advisors.addAll(classAdvisors);
39         .......
40         return advisors;
41     }

 

 1     public List<Advisor> getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory) {
 2     //獲取我們的注解類
 3         Class<?> aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
 4         //獲取名稱
 5         String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName();
 6         validate(aspectClass);
 7 
 8         // We need to wrap the MetadataAwareAspectInstanceFactory with a decorator
 9         // so that it will only instantiate once.
10         MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory =
11                 new LazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory);
12 
13         List<Advisor> advisors = new ArrayList<>();
14         //這里回圈獲取我們類的方法,找到除Pointcut注解外的注解方法
15         for (Method method : getAdvisorMethods(aspectClass)) {
16         //決議方法,如果找到Around.class, Before.class, After.class, AfterReturning.class, AfterThrowing.class注解,則回傳InstantiationModelAwarePointcutAdvisorImpl生成類
17             Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, advisors.size(), aspectName);
18             if (advisor != null) {
19                 advisors.add(advisor);
20             }
21         }
22 
23         .......
24 
25         return advisors;
26     }

  自此,我們的注解就決議完成了,不過心細的同學發現了,直決議了除Pointcut注解外的注解,Pointcut直接沒有決議啊,這個注解一般我們都配置在了Around等注解里面,會有決議類去決議這個方法的,我們看看實體化后的后置處理器邏輯再

 1     @Override
 2     public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
 3             throws BeansException {
 4 
 5         Object result = existingBean;
 6         //遍歷所有后置處理器,但是我們只看AbstractAutoProxyCreator類的
 7         for (BeanPostProcessor processor : getBeanPostProcessors()) {
 8             Object current = processor.postProcessAfterInitialization(result, beanName);
 9             if (current == null) {
10                 return result;
11             }
12             result = current;
13         }
14         return result;
15     }
 1     //呼叫此方法
 2     protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
 3         if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
 4             return bean;
 5         }
 6         if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
 7             return bean;
 8         }
 9         if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
10             this.advisedBeans.put(cacheKey, Boolean.FALSE);
11             return bean;
12         }
13 
14         // Create proxy if we have advice.
15         //是否有注解
16         Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
17         if (specificInterceptors != DO_NOT_PROXY) {
18             this.advisedBeans.put(cacheKey, Boolean.TRUE);
19             //有則創建代理類回傳
20             Object proxy = createProxy(
21                     bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
22             this.proxyTypes.put(cacheKey, proxy.getClass());
23             return proxy;
24         }
25 
26         this.advisedBeans.put(cacheKey, Boolean.FALSE);
27         return bean;
28     }

  為了清晰邏輯,中間的環節代碼就不看了,直接看一下回傳的是啥,

 1     public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
 2     //config.isProxyTargetClass()這個默認時true,為什么走cglib代理呢?
 3         if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
 4             Class<?> targetClass = config.getTargetClass();
 5             if (targetClass == null) {
 6                 throw new AopConfigException("TargetSource cannot determine target class: " +
 7                         "Either an interface or a target is required for proxy creation.");
 8             }
 9             if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
10                 return new JdkDynamicAopProxy(config);
11             }
12             return new ObjenesisCglibAopProxy(config);
13         }
14         else {
15             return new JdkDynamicAopProxy(config);
16         }
17     }

  為什么spring默認走cglib代理呢?我們大家可能還知道一個注解是@EnableAspectJAutoProxy,其實這個才是控制的開關,如果我們寫成false的話是走jdk代理的,但是為什么我們自己的配置類配置EnableAspectJAutoProxy注解了也是無效的呢?這時候就要看一下AopAutoConfiguration自動配置類了,為了防止大家看暈,博主也畫了一張草圖:

  https://www.processon.com/view/link/6134bef3e401fd1fb6a91dc6

 

 1 public class AopAutoConfiguration {
 2     //jdk和cglib都有注解,但是默認只有一個生效了,就是CglibAutoProxyConfiguration,因為ConditionalOnProperty注解說明了一起
 3     @Configuration
 4     @EnableAspectJAutoProxy(proxyTargetClass = false)
 5     @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "https://www.cnblogs.com/guoxiaoyu/p/false", matchIfMissing = false)
 6     public static class JdkDynamicAutoProxyConfiguration {
 7 
 8     }
 9 
10     @Configuration
11     @EnableAspectJAutoProxy(proxyTargetClass = true)
12     @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "https://www.cnblogs.com/guoxiaoyu/p/true", matchIfMissing = true)
13     public static class CglibAutoProxyConfiguration {
14 
15     }
16 
17 }

 

  當我們不去在組態檔中明確標明spring.aop.proxy-target-class屬性時,只有就是CglibAutoProxyConfiguration是生效的,怕有些小伙伴不知道ConditionalOnProperty注解的作用,博主就簡單帶帶大家看一下,熟悉同學可以自行略過,在spring決議配置類時,就會決議該注解

 1     //這是校驗配置類的時候決議的,路徑-》org.springframework.context.annotation.ConditionEvaluator#shouldSkip
 2     public boolean shouldSkip(@Nullable AnnotatedTypeMetadata metadata, @Nullable ConfigurationPhase phase) {
 3     //由于jdk和cglib類都有Conditional的子注解,所以都通過了
 4         if (metadata =https://www.cnblogs.com/guoxiaoyu/p/= null || !metadata.isAnnotated(Conditional.class.getName())) {
 5             return false;
 6         }
 7 
 8         if (phase == null) {
 9             if (metadata instanceof AnnotationMetadata &&
10                     ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata) metadata)) {
11                 return shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION);
12             }
13             return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
14         }
15 
16         List<Condition> conditions = new ArrayList<>();
17         //找到ConditionalOnProperty注解
18         for (String[] conditionClasses : getConditionClasses(metadata)) {
19             for (String conditionClass : conditionClasses) {
20                 Condition condition = getCondition(conditionClass, this.context.getClassLoader());
21                 conditions.add(condition);
22             }
23         }
24 
25         AnnotationAwareOrderComparator.sort(conditions);
26 
27         for (Condition condition : conditions) {
28             ConfigurationPhase requiredPhase = null;
29             if (condition instanceof ConfigurationCondition) {
30                 requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
31             }
32             //開始檢驗是否匹配
33             if ((requiredPhase == null || requiredPhase == phase) && !condition.matches(this.context, metadata)) {
34                 return true;
35             }
36         }
37 
38         return false;
39     }
 1     public final boolean matches(ConditionContext context,
 2             AnnotatedTypeMetadata metadata) {
 3         String classOrMethodName = getClassOrMethodName(metadata);
 4         try {
 5         //走這里查看OnPropertyCondition匹配即可
 6             ConditionOutcome outcome = getMatchOutcome(context, metadata);
 7             logOutcome(classOrMethodName, outcome);
 8             recordEvaluation(context, classOrMethodName, outcome);
 9             return outcome.isMatch();
10         }
11         ......
12     }
 1         private void collectProperties(PropertyResolver resolver, List<String> missing,
 2                 List<String> nonMatching) {
 3             for (String name : this.names) {
 4                 String key = this.prefix + name;
 5                 if (resolver.containsProperty(key)) {
 6                     if (!isMatch(resolver.getProperty(key), this.havingValue)) {
 7                         nonMatching.add(name);
 8                     }
 9                 }
10                 else {
11                 //直接查看關鍵代碼,如果組態檔中沒有該屬性,查看是否注解中寫了matchIfMissing屬性,而我們的cglib是true,所以,不會missing,而是裝配起來了,所以默認走cglib代理
12                     if (!this.matchIfMissing) {
13                         missing.add(name);
14                     }
15                 }
16             }
17         }

  現在我們的注解不僅加載完了,而且被注解表明的也生成了代理類,我們看看切面注解是如何生效的,我們就以cglib舉例了,jdk類似

 1 //CglibAopProxy
 2 public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
 3             Object oldProxy = null;
 4             boolean setProxyContext = false;
 5             Object target = null;
 6             TargetSource targetSource = this.advised.getTargetSource();
 7             try {
 8                 .....
 9                 //獲取是否有攔截鏈,并不是我們的請求攔截器,這里把切面認為是一種攔截器了
10                 List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
11                 Object retVal;
12                 // Check whether we only have one InvokerInterceptor: that is,
13                 // no real advice, but just reflective invocation of the target.
14                 if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
15                     // We can skip creating a MethodInvocation: just invoke the target directly.
16                     // Note that the final invoker must be an InvokerInterceptor, so we know
17                     // it does nothing but a reflective operation on the target, and no hot
18                     // swapping or fancy proxying.
19                     Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
20                     retVal = methodProxy.invoke(target, argsToUse);
21                 }
22                 else {
23                     // We need to create a method invocation...
24                     //主要就是走后面的.proceed()方法
25                     retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
26                 }
27                 retVal = processReturnType(proxy, target, method, retVal);
28                 return retVal;
29             .....
30                 }
31             }
32         }
 1     //這里就像走我們的請求過濾器一樣,每個攔截器都走一遍,最后都呼叫proceed()再回到這個方法,直到++this.currentInterceptorIndex到頭終止
 2     public Object proceed() throws Throwable {
 3         //    We start with an index of -1 and increment early.
 4         if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
 5             return invokeJoinpoint();
 6         }
 7 
 8         Object interceptorOrInterceptionAdvice =
 9                 this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
10         if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
11             // Evaluate dynamic method matcher here: static part will already have
12             // been evaluated and found to match.
13             InterceptorAndDynamicMethodMatcher dm =
14                     (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
15             if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
16             //別的我們不看,就看我們自己定義的@around
17                 return dm.interceptor.invoke(this);
18             }
19             else {
20                 // Dynamic matching failed.
21                 // Skip this interceptor and invoke the next in the chain.
22                 return proceed();
23             }
24         }
25         else {
26             // It's an interceptor, so we just invoke it: The pointcut will have
27             // been evaluated statically before this object was constructed.
28             return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
29         }
30     }

  呼叫反射的時候,就會發現我們的around中才會去決議pointcut方法,因為我們在around注解里面寫了,具體設這個類PointcutParser#parsePointcutExpression去進行決議的,將pointcut的運算式放入到around中作為引數傳遞,

  對此,Spring AOP就全部講解完畢了,里面為了減少文章篇幅,去掉了一些中間的跳轉代碼,具體可以看一下,博主發的草圖,草圖中所以的邏輯都很清晰,也貼了一些關鍵性的邏輯代碼,希望大家可以在深入了解了解,


 

ps:以上內容,純屬個人見解,有任何問題下方評論!關注博主公眾號,你想要的都有,每周不停更哦!原創撰寫不易,轉載請說明出處!

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/297710.html

標籤:Java

上一篇:spring boot 系列之七:SpringBoot整合Mybatis

下一篇:【曹工雜談】Maven插件除錯方法

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more