测试效果:
本实验的逻辑在于: 1.通过agent的premain,将jvm暴露的instrumentation保存起来,到一个static的field里。 2.这样,在main方法执行前,我们已经把 instrumentation 存到了一个可以地方了,后续可以供我们使用。 3.然后,我们再把aspectJ的classFileTransformer设置到第二步获取到的instrumentation里。 执行步骤: 1.mvn clean package,得到jar包:spring-aspectj-integration-1.0-SNAPSHOT.jar 2.把aspectjweaver-1.8.2.jar和spring-instrument-4.3.7.RELEASE.jar拷贝到和本jar包同路径下 3.cmd下执行: java -javaagent:spring-instrument-4.3.7.RELEASE.jar -cp spring-aspectj-integration-1.0-SNAPSHOT.jar;aspectjweaver-1.8.2.jar foo.Main代码呢,我放在了:
https://gitee.com/ckl111/spring-boot-first-version-learn/tree/225530ad7fe1f1f6cd14e5ef5a954d8642ecefb5/all-demo-in-spring-learning/spring-aspectj-integration
总结万丈高楼平地起,如果没有一个好的地基,多高的高楼也盖不起来。上面我们就详细讲了ltw依赖的两种底层实现。
容器环境,主要靠自定义classloader,这种呢,启动时,无需加javaagent参数;
非容器环境,则主要靠java instrumentation,这种就要加javaagent,里面的jar呢,可以直接使用aspectJ的aspectjweaver.jar;也可以直接使用spring-instrumentation.jar。
spring的使用时,如果是在非容器环境下,其实就是使用的spring-instrumentation.jar。
这部分呢,我截取了spring官方文档的一段话:
Generic Java applicationsWhen class instrumentation is required in environments that do not support or are not supported by the existing LoadTimeWeaver implementations, a JDK agent can be the only solution. For such cases, Spring provides InstrumentationLoadTimeWeaver, which requires a Spring-specific (but very general) VM agent, org.springframework.instrument-{version}.jar (previously named spring-agent.jar).
To use it, you must start the virtual machine with the Spring agent, by supplying the following JVM options:
-javaagent:/path/to/org.springframework.instrument-{version}.jarNote that this requires modification of the VM launch script which may prevent you from using this in application server environments (depending on your operation policies). Additionally, the JDK agent will instrument the entire VM which can prove expensive.
For performance reasons, it is recommended to use this configuration only if your target environment (such as Jetty) does not have (or does not support) a dedicated LTW.
翻译:简单来说,就是,当class instrumentation 需要时,JDK agent就是唯一选择。此时,spring提供了InstrumentationLoadTimeWeaver,这时,需要指定一个agent,org.springframework.instrument-{version}.jar。
使用方式如下:
-javaagent:/path/to/org.springframework.instrument-{version}.jar这样呢,就会需要修改VM的启动脚本。而且,JDK agent会instrument整个VM,代价高昂。为了性能考虑,推荐只有在不得不使用时,才使用这种方式。
总的来说,经过这两讲,把ltw的基础讲清楚了,下一讲,看看spring是怎么实现的,有了这些基础,那会很轻松。