通俗地理解下AOP中的一些概念

aopalliance中的概念:

Advice:

Advice -> Interceptor -> MethodInterceptor:核心是Advice,翻译过来就是建议,也就是具体的切面代码,这个是静态的。

Joinpoint:

Joinpoint-> Invocation -> MethodInvocation:核心是Joinpoint,翻译过来是切入点,也就是具体的一个切入上下文,这个是运行时的。

二者的关系:

advice is the action to take at a joinpoint,advice是在joinpoint里要执行的操作(我们的增强aop代码)。可以参考MethodInterceptor

public interface MethodInterceptor extends Interceptor {

	@Nullable
	Object invoke(@Nonnull MethodInvocation invocation) throws Throwable;
}

Spring AOP中的概念:

Spring的AOP概念是基于aopalliance,在Advice和Joinpoint的基础上增加了以下概念。

Pointcut:

pointcut->StaticMethodMatcherPointcut

public interface Pointcut {

	ClassFilter getClassFilter();


	MethodMatcher getMethodMatcher();
}

其实就是一个方法匹配器,定位到一个我们需要切入的点(某个类的某个方法)。

Advisor:

Advisor-> PointcutAdvisor

Advice的持有者,主要参考子接口PointcutAdvisor

public interface Advisor {

	Advice EMPTY_ADVICE = new Advice() {};

	Advice getAdvice();

	boolean isPerInstance();
}

public interface PointcutAdvisor extends Advisor {

	Pointcut getPointcut();

}

我这里拿权游的一个场景做类比:

小恶魔提利昂·兰尼斯特(Advisor)建议龙妈丹妮莉丝·坦格利安在攻陷君临城的时候(Pointcut)宽恕所有平民(Advice)

抽出来就是,一个建言者(Advisor)建议在某时某地某人(Pointcut)做某事(Advice)。

这里重点说下Joinpoint和Pointcut的区别:

Pointcut是一个静态的概念:上述例子中的“龙妈丹妮莉丝·坦格利安在攻陷君临城的时候”,这个只是标识了这个点,并不一定已经发生了。

Joinpoint是一个运行时的概念:表示真到了这个Pointcut的时候,包含了此时的上下文环境,方法被调用的参数等。

Advised:

如果你拿到一个bean,想知道它是不是被增强过了,可以判断这个bean是不是Advised的子类,也就是这是所有被增强过的代理对象的顶级接口。bean被多个切面增强,其实是在这里存在一个Advisor链。在实际运行的时候依次执行Advisor链中的(符合其Pointcut)的Advice。

public interface Advised extends TargetClassAware {

	boolean isFrozen();

	boolean isProxyTargetClass();

	Class<?>[] getProxiedInterfaces();

	boolean isInterfaceProxied(Class<?> intf);

	void setTargetSource(TargetSource targetSource);

	TargetSource getTargetSource();

	void setExposeProxy(boolean exposeProxy);

	boolean isExposeProxy();

	void setPreFiltered(boolean preFiltered);

	boolean isPreFiltered();

	Advisor[] getAdvisors();

	default int getAdvisorCount() {
		return getAdvisors().length;
	}

	void addAdvisor(Advisor advisor) throws AopConfigException;

	void addAdvisor(int pos, Advisor advisor) throws AopConfigException;

	boolean removeAdvisor(Advisor advisor);

	void removeAdvisor(int index) throws AopConfigException;

	int indexOf(Advisor advisor);

	boolean replaceAdvisor(Advisor a, Advisor b) throws AopConfigException;

	void addAdvice(Advice advice) throws AopConfigException;

	void addAdvice(int pos, Advice advice) throws AopConfigException;

	boolean removeAdvice(Advice advice);

	int indexOf(Advice advice);

	String toProxyConfigString();

}

文章到这里就基本结束,本文只是对Spring AOP中的一些核心概念做了简单的介绍,如果你是AOP的初学者,这对你理解那一堆看起来差不多的概念应该会有所帮助,如果你也觉得有用,点个赞再走呗

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值