Spring 框架核心 AOP(LTW) 概念随笔

AOP <= Load-time Weaving (LTW) 来自 AspectJ项目

在Spring中使用LTW技术

  • 命名空间 <context:load-time-weaver/>
  • JVM参数 -javaagent:/path/to/jar/spring-agent.jar

context:load-time-weave

会把 AspectJ的LTW放到类加载器当中,所有的类都将能匹配到定义好的 Pointcut

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:load-time-weaver />
    
    <bean id="processor" class="org.springbyexample.aspectjLoadTimeWeaving.Processor" />
    
</beans>
复制代码

AspectJ配置

aspectJ会自动加载 META-INF/aop.xml,有关 weaver 和 aspects 的配置示例

                
<!DOCTYPE aspectj PUBLIC
        "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<aspectj>
    <weaver>
        <!-- only weave classes in this package -->
        <!-- 声明给 weaver 哪里有 weave 要处理 -->
        <include within="org.springbyexample.aspectjLoadTimeWeaving.*" />
    </weaver>
    <aspects>
        <!-- use only this aspect for weaving -->
        <!-- 这里是提议 Advice -->
        <aspect name="org.springbyexample.aspectjLoadTimeWeaving.PerformanceAdvice" />
    </aspects>
</aspectj>
             
复制代码
提议 Advice
@Aspect
public class PerformanceAdvice {

    @Pointcut("execution(public * org.springbyexample.aspectjLoadTimeWeaving..*.*(..))")
    public void aspectjLoadTimeWeavingExamples() {
    }

    @Around("aspectjLoadTimeWeavingExamples()")
    public Object profile(ProceedingJoinPoint pjp) throws Throwable {
        final Logger logger = LoggerFactory.getLogger(pjp.getSignature().getDeclaringType());

        StopWatch sw = new StopWatch(getClass().getSimpleName());

        try {
            sw.start(pjp.getSignature().getName());

            return pjp.proceed();
        } finally {
            sw.stop();

            logger.debug(sw.prettyPrint());
        }
    }

}
复制代码

知识点 TBC

  • 切入点使用的是 SpEL 语法,有待新建一篇掘金文章



不好意思本来有下一篇的,Spring版本AOP介绍,看了一下官方文档写得是很全,

但是我建议呢,还是找本书看 ,《Spring实战 第4版》,根据例子来学很容易懂。

实战过就不再恐惧抽象,AOP编程太强大了,一篇文章说清楚不行。

转载于:https://juejin.im/post/5cdfc12b5188253c567342b1

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值