Spring的LoadTimeWeaver(代码织入)(转)

AspectJ LTW实战
本文介绍AspectJ的类加载期织入(LoadTimeWeaving,简称LTW)并提供了一个实战案例。通过LTW可以在类加载到JVM时织入切面,文中详细解释了如何配置LTW以及创建切面来监控方法执行效率。

https://www.cnblogs.com/wade-luffy/p/6073702.html

在Java 语言中,从织入切面的方式上来看,存在三种织入方式:编译期织入、类加载期织入和运行期织入。编译期织入是指在Java编译期,采用特殊的编译器,将切面织入到Java类中;而类加载期织入则指通过特殊的类加载器,在类字节码加载到JVM时,织入切面;运行期织入则是采用CGLib工具或JDK动态代理进行切面的织入。

AspectJ采用编译期织入和类加载期织入的方式织入切面,是语言级的AOP实现,提供了完备的AOP支持。它用AspectJ语言定义切面,在编译期或类加载期将切面织入到Java类中。  

AspectJ提供了两种切面织入方式,第一种通过特殊编译器,在编译期,将AspectJ语言编写的切面类织入到Java类中,可以通过一个Ant或Maven任务来完成这个操作;第二种方式是类加载期织入,也简称为LTW(Load Time Weaving)。 (只讲解第二种)

如何使用Load Time Weaving?首先,需要通过JVM的-javaagent参数设置LTW的织入器类包,以代理JVM默认的类加载器;第二,LTW织入器需要一个 aop.xml文件,在该文件中指定切面类和需要进行切面织入的目标类。

下面将通过一个简单的例子在描述如何使用LTW:

例子所作的是记录被调用方法的执行时间和CPU使用率。其实这在实际生产中很有用,与其拉一堆性能测试工具,不如动手做个简单的分析切面,使我们能很快得到一些性能指标。我指的是没有硬性的性能测试需求下。

首先我们编写一个被织入的受体类,也就是被拦截的对象。

复制代码
public class DemoBean {
    public void run1() { System.out.println("run1..."); } public void run2() throws Exception { TimeUnit.SECONDS.sleep(2); System.out.println("run2..."); } }
复制代码

接着,我们编写分析方法执行效率的切面。

复制代码
@Aspect
public class ProfileAspect {
    @Around("profileMethod()")
    public Object profile(ProceedingJoinPoint pjp) throws Throwable { StopWatch sw = new StopWatch(getClass().getName()); try { sw.start(pjp.getSignature().getName()); return pjp.proceed(); } finally { sw.stop(); System.err.println(sw.prettyPrint()); } } @Pointcut("execution(public * org.codetree.core.spring.loadtimeweaver.*.*(..))") public void profileMethod() { System.out.println("profileMethod.."); } }
复制代码

aop.xml。这个文件要求放在META-INF/aop.xml路径下,以告知AspectJ Weaver我们需要把ProfilingAspect织入到应用的哪些类中。

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd"> <aspectj> <weaver> <!-- only weave classes in your application-specific packages --> <include within="org.codetree.core.spring.loadtimeweaver.*" /> </weaver> <aspects> <!-- weave in just these aspects --> <aspect name="org.codetree.core.spring.loadtimeweaver.ProfileAspect" /> </aspects> </aspectj>
复制代码

spring的配置文件

复制代码
<?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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:load-time-weaver aspectj-weaving="autodetect" /> <context:component-scan base-package="org.codetree.core.spring.loadtimeweaver" use-default-filters="false"> <context:include-filter type="regex" expression="org.codetree.core.spring.loadtimeweaver.*" /> <context:exclude-filter type="regex" expression="org.codetree.core.spring.loadtimeweaver.Main" /> </context:component-scan> </beans>
复制代码

或者

@EnableLoadTimeWeaving(aspectjWeaving=AspectJWeaving.AUTODETECT)

@EnableAspectJAutoProxy

@ComponentScan

通过 <context:load-time-weaver  aspectj-weaving="on" /> 使 spring开启 loadtimeweaver, 注意 aspectj-weaving 有三个选项 : on, off, auto-detect, 如果设置为 auto-detect, spring 将会在 classpath 中查找aspejct 需要的 META-INF/aop.xml, 如果找到则开启 aspectj weaving,这个逻辑在LoadTimeWeaverBeanDefinitionParser#isAspectJWeavingEnabled方法中。

测试类

复制代码
public class Main {
    public static void main(String[] args) throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/spring/loadtimeweaver/loadtimeweaver.xml"); DemoBean demoBean = context.getBean(DemoBean.class); demoBean.run1(); demoBean.run2(); } } 
复制代码

结果 

复制代码
输出结果如下:

run1...

StopWatch 'ProfilingAspect': running time (millis) = 0

-----------------------------------------

ms     %     Task name

-----------------------------------------

0001  100%  run1
复制代码

如果想不加JVM的-javaagent参数可以进行如下替换:

复制代码
public class ExtInstrumentationLoadTimeWeaver extends InstrumentationLoadTimeWeaver(默认的weaver) {  
    @Override  
    public void addTransformer(ClassFileTransformer transformer) { try { super.addTransformer(transformer); } catch (Exception e) {吃掉无关异常不抛出} } } 
复制代码

spring的配置文件

复制代码
<?xml version="1.0" encoding="GBK"?>  
   
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> 
   <context:load-time-weaver weaver-class="com.shansun.multidemo.spring.ExtInstrumentationLoadTimeWeaver" aspectj-weaving="autodetect" /> <context:component-scan base-package="com.shansun.multidemo"></context:component-scan> </beans>
复制代码

 

 作者在写AOP对class的所有方法做拦截trace的时候发现嵌套调用的方法无法被拦截,因为在被拦截实体中再调用实体里的其他方法的时候,不是指向代理对象,而是当前对象, 于是找资料,在三种织入方式:编译期织入、类加载期织入和运行期织入,而spring里不管是用动态代理还是cglib都是运行期织入,关于这点美团的trace就是用加载器织入实现

转载于:https://www.cnblogs.com/devilwind/p/8707261.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值