Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the function of EnableAspectJAutoProxy in Springboot

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article is to share with you about the role of EnableAspectJAutoProxy in Springboot, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

Summary:

The two core technologies of Spring Framwork are IOC and AOP,AOP, which have a large number of applications in Spring's product line. If reflection is the basis of your access to the advanced, then the agent is your strength to stand on the high level. The essence of AOP is the familiar CGLIB dynamic agent technology, which must have been used more or less in daily work, but the secret behind it is worth pondering. This paper mainly introduces a running process of Spring AOP from the running process of Spring AOP, combined with a certain source code. Know it, know why, in order to better control this core technology.

@ Target ({ElementType.TYPE}) @ Retention (RetentionPolicy.RUNTIME) @ Documented @ Import ({AspectJAutoProxyRegistrar.class}) public @ interface EnableAspectJAutoProxy {/ / indicates whether this class uses CGLIB agent or JDK dynamic agent boolean proxyTargetClass () default false / * * @ since 4.3.1 Agent exposure: solve the situation where internal calls cannot use a proxy. Default is false means no processing * true: this proxy can obtain a copy of the proxy object through AopContext.currentProxy () (inside ThreadLocal) Thus we can easily get the current proxy object (convenient when dealing with transactions) in the context of the Spring framework * it must be true to call the AopContext method. Otherwise, the error report: Cannot find current proxy: Set 'exposeProxy' property on Advised to' true' to make it available. * / boolean exposeProxy () default false;}

All EnableXXX driver technologies depend on his @ Import, so the most important thing above is this @ Import (AspectJAutoProxyRegistrar.class). Let's take a look at it.

Class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {AspectJAutoProxyRegistrar () {} public void registerBeanDefinitions (AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {/ / registered an annotation-based automatic proxy creator AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary (registry); AnnotationAttributes enableAspectJAutoProxy = AnnotationConfigUtils.attributesFor (importingClassMetadata, EnableAspectJAutoProxy.class) If (enableAspectJAutoProxy! = null) {/ / indicates that CGLIB if (enableAspectJAutoProxy.getBoolean ("proxyTargetClass")) {AopConfigUtils.forceAutoProxyCreatorToUseClassProxying (registry) is forcibly specified. } / / forcibly expose Bean's proxy object to AopContext if (enableAspectJAutoProxy.getBoolean ("exposeProxy")) {AopConfigUtils.forceAutoProxyCreatorToExposeProxy (registry);}}

AspectJAutoProxyRegistrar is an automatic proxy creator for item container registration

Nullable public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary (BeanDefinitionRegistry registry, @ Nullable Object source) {return registerOrEscalateApcAsRequired (AnnotationAwareAspectJAutoProxyCreator.class, registry, source);}

Note: the annotation agent creator of the spring container is AnnotationAwareAspectJAutoProxyCreator

@ Nullable private static BeanDefinition registerOrEscalateApcAsRequired (Class cls, BeanDefinitionRegistry registry, @ Nullable Object source) {Assert.notNull (registry, "BeanDefinitionRegistry must not be null") / / if we define such an automatic proxy creator ourselves, we will use our custom if (registry.containsBeanDefinition ("org.springframework.aop.config.internalAutoProxyCreator")) {BeanDefinition apcDefinition = registry.getBeanDefinition ("org.springframework.aop.config.internalAutoProxyCreator") If (! cls.getName (). Equals (apcDefinition.getBeanClassName () {int currentPriority = findPriorityForClass (apcDefinition.getBeanClassName ()); / * * user registered creator must be one of InfrastructureAdvisorAutoProxyCreator * AspectJAwareAdvisorAutoProxyCreator,AnnotationAwareAspectJAutoProxyCreator * / int requiredPriority = findPriorityForClass (cls) If (currentPriority

< requiredPriority) { apcDefinition.setBeanClassName(cls.getName()); } } return null; } //若用户自己没有定义,那就用默认的AnnotationAwareAspectJAutoProxyCreator RootBeanDefinition beanDefinition = new RootBeanDefinition(cls); beanDefinition.setSource(source); //此处注意,增加了一个属性:最高优先级执行,后面会和@Async注解一起使用的时候起关键作用 beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE); beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition); return beanDefinition; } 我们就成功的注入了一个Bean:AnnotationAwareAspectJAutoProxyCreator 基于注解的自动代理创建器 Spring中自动创建代理器

Thus, Spring uses BeanPostProcessor to automatically generate proxies. The implementation class of the BeanPostProcessor-based automatic proxy creator generates a proxy instance for the matching Bean when the container instantiates the Bean according to some rules.

AbstractAutoProxyCreator is an abstract implementation of the automatic proxy creator. Most importantly, it implements the SmartInstantiationAwareBeanPostProcessor interface, so it intervenes in the process of instantiating the Spring IoC container Bean.

SmartInstantiationAwareBeanPostProcessor inherits InstantiationAwareBeanPostProcessor, so its main responsibility is to execute all InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation before initializing bean. Whoever first returns a Bean that is not null will not be executed later. Then BeanPostProcessor#postProcessAfterInitialization will be executed.

Protected Object getEarlyBeanReference (String beanName, RootBeanDefinition mbd, Object bean) {Object exposedObject = bean If (! mbd.isSynthetic () & & hasInstantiationAwareBeanPostProcessors ()) {for (BeanPostProcessor bp: getBeanPostProcessors ()) {if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp ExposedObject = ibp.getEarlyBeanReference (exposedObject, beanName);} return exposedObject;}

Note: this method is one of the rings in spring's three-tier cache. It will trigger when you call Object earlySingletonReference = getSingleton (beanName, false). In fact, there is also a place where exposedObject = initializeBean (beanName, exposedObject, mbd); it will also trigger the return of a proxy object.

Protected Object initializeBean (final String beanName, final Object bean, @ Nullable RootBeanDefinition mbd) {if (System.getSecurityManager ()! = null) {AccessController.doPrivileged ((PrivilegedAction) ()-> {invokeAwareMethods (beanName, bean); return null }, getAccessControlContext ();} else {invokeAwareMethods (beanName, bean);} Object wrappedBean = bean If (mbd = = null | |! mbd.isSynthetic ()) {wrappedBean = applyBeanPostProcessorsBeforeInitialization (wrappedBean, beanName);} try {invokeInitMethods (beanName, wrappedBean, mbd) } catch (Throwable ex) {throw new BeanCreationException ((mbd! = null?) Mbd.getResourceDescription (): null), beanName, "Invocation of init method failed", ex);} if (mbd = = null | |! mbd.isSynthetic ()) {wrappedBean = applyBeanPostProcessorsAfterInitialization (wrappedBean, beanName);} return wrappedBean }

Emphasis: although these two places have post-enhancement, the AsyncAnnotationBeanPostProcessor used by @ Async is not the implementation class of SmartInstantiationAwareBeanPostProcessor, so it will lead to inconsistency between @ Transactional and @ Async when dealing with circular dependencies. For circular dependencies, there will be separate chapters to share.

This is what the role of EnableAspectJAutoProxy in Springboot is, and the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report