本文主要记录下如何创建一个简单的java Agent,并配置运行。

1.创建Agent类

package com.java4all.grouth.agent;

import java.lang.instrument.Instrumentation;

/**
* @description: java Agent
* @author: IT云清
*/
public class MyAgent {

public static void premain(String agentArgs, Instrumentation instrumentation) {
System.out.println("This is MyAgent,args:"+agentArgs);
}

}

2.MANIFEST.MF 配置文件

这里在src/main/resources/META-INF/下创建一个MANIFEST.MF文件,指定Agent class和版本相关信息。注意最后一行需要一个空行,否则idea会报错。

Manifest-Version: 1.0
Premain-Class: com.java4all.grouth.agent.MyAgent
Can-Redefine-Classes: true
Can-Retransform-Classes: true

3.打包配置

在pom.xml中配置打包信息

<build>
<finalName>my-agent</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<archive>
<index>true</index>
<manifestFile>
src/main/resources/META-INF/MANIFEST.MF
</manifestFile>
<manifest>
<addDefaultImplementationEntries/>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>

4.打包

mvn clean package

会生成一个jar

java agent开发_agent

5.应用

这里以idea为例,配置VM options参数

java agent开发_maven_02


参数格式为:-javaagent:/Agent的jar路径=参数

例如:

-javaagent:/Users/ityunqing/mycode/grouth/target/my-agent.jar=IT云清

项目启动后,就会看到,在main方法执行前,执行了premain方法。

java agent开发_java_03