序
AOP和IOC是J2EE的两大基石,传统的AOP是在代码层面的,在bytecode层面也有aop技术,就是基于JVMTI(JVM TOOL INTERFACE)的instrument技术。这里主要记录下instrument入门使用。
agent实例
public class SimpleJavaAgent {
public static void premain(String args, Instrumentation instrumentation){
System.out.println("Premain");
System.out.println("Number of classes loaded: "+instrumentation.getAllLoadedClasses().length);
// instrumentation.addTransformer(new DemoTransformer());
}
}
maven打包
<build>
<plugins>
<!--<plugin>-->
<!--<groupId>org.apache.maven.plugins</groupId>-->
<!--<artifactId>maven-jar-plugin</artifactId>-->
<!--<version>2.6</version>-->
<!--<configuration>-->
<!--<outputDirectory>${basedir}</outputDirectory>-->
<!--<archive>-->
<!--<!–<index>true</index>–>-->
<!--<manifest>-->
<!--<addClasspath>true</addClasspath>-->
<!--</manifest>-->
<!--<manifestEntries>-->
<!--<Premain-Class>com.geekyarticles.instrumentation.SimpleJavaAgent</Premain-Class>-->
<!--</manifestEntries>-->
<!--</archive>-->
<!--</configuration>-->
<!--</plugin>-->
<!--mvn assembly:single -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<outputDirectory>${basedir}</outputDirectory>
<archive>
<index>true</index>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestEntries>
<Premain-Class>com.geekyarticles.instrumentation.SimpleJavaAgent</Premain-Class>
</manifestEntries>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
执行mvn assembly:single
main实例
public class SimpleJavaAgentDemo {
public static void main(String[] args) {
System.out.println("Hello! its the main method");
}
}
exec的maven配置
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable>java</executable>
<arguments>
<!--<argument>-Xmx128m</argument>-->
<argument>-javaagent:"${project.parent.basedir}${file.separator}simple-agent${file.separator}simple-agent-1.0-SNAPSHOT-jar-with-dependencies.jar"</argument>
<argument>-classpath</argument>
<classpath/>
<argument>com.geekyarticles.instrumentation.SimpleJavaAgentDemo</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>
执行mvn compile,然后mvn exec:exec
工程github