栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

AOP源码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

AOP源码

基本概念

横切关注点

切面(Aspect)

连接点(JoinPoint)

切入点(PointCut)

通知(Advice)

目标对象(Target)

织入(Weave)

引入(Introduction)

示例代码:

@Aspect
@Component
public class AopTest {

    @Pointcut("execution(* com.example.sourcecodelearning.service.*(..))")
    public void pointCut() {
    }

    @Before(value = "pointCut()")
    public void mBefore(JoinPoint joinPoint) {
        System.out.println("============= processed Before: " + joinPoint.getSignature().getName());
    }

    @After(value = "pointCut()")
    public void mAfter(JoinPoint joinPoint) {
        System.out.println("============= processed After: " + joinPoint.getSignature().getName());
    }

    @AfterReturning(value = "pointCut()")
    public void mReturning(JoinPoint joinPoint) {
        System.out.println("============= processed AfterReturning: " + joinPoint.getSignature().getName());
    }

    @AfterThrowing(value = "pointCut()")
    public void mAfterThrowing(JoinPoint joinPoint) {
        System.out.println("============= processed AfterThrowing: " + joinPoint.getSignature().getName());
    }
}
@Component
public class TestServiceImpl implements TestService {
    @Override
    public String businessFlow() throws Exception {
        return "businessFlow finished";
    }
}
 sprintboot引入

     默认使用 JDK 动态代理,如果为proxyTargetClass = true, 代理目标对象时强制使用 CGLIB 代理。 JDK代理是基于接口的实现,代理类继承Proxy,实现接口。而CGLIB继承代理类来实现。运行期间生成的代理对象是针对目标类扩展的子类,底层是依靠ASM操作字节码来实现的,性能比JDK强。
     如果为exposeProxy = true, 暴露代理对象,这样就可以使用 AopContext.currentProxy() 方法获取当前代理的对象。这样同个类的a方法调用b方法,b方法也可开启新事务增强

建议尽量使用JDK!使用CGLIB也需要考虑以下两个问题:

1.无法通知Final修饰的方法 2.需要将CGLIB包放在classpath下面

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {
	boolean proxyTargetClass() default false;
	boolean exposeProxy() default false;
}

由AspectJAutoProxyRegistrar创建

class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(
            AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);
        AnnotationAttributes enableAspectJAutoProxy =
                AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
        if (enableAspectJAutoProxy != null) {
            if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {
                AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
            }
            if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {
                AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
            }
        }
    }
}

registerAspectJAnnotationAutoProxyCreatorIfNecessary这里重要的是注册AnnotationAwareAspectJAutoProxyCreator

在父类AbstractAutoProxyCreator的postProcessAfterInitialization进行实例化

public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
		if (bean != null) {
			Object cacheKey = getCacheKey(bean.getClass(), beanName);
			if (this.earlyProxyReferences.remove(cacheKey) != bean) {
				return wrapIfNecessary(bean, beanName, cacheKey);
			}
		}
		return bean;
	}


protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
		if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
			return bean;
		}
		if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
			return bean;
		}
		if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
			this.advisedBeans.put(cacheKey, Boolean.FALSE);
			return bean;
		}

		// Create proxy if we have advice.
		Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
		if (specificInterceptors != DO_NOT_PROXY) {
			this.advisedBeans.put(cacheKey, Boolean.TRUE);
			Object proxy = createProxy(
					bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
			this.proxyTypes.put(cacheKey, proxy.getClass());
			return proxy;
		}

		this.advisedBeans.put(cacheKey, Boolean.FALSE);
		return bean;
	}

===============

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/914696.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号