赞
踩
本文主要记录下如何创建一个简单的java 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); } }
这里在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
在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>
mvn clean package
会生成一个jar
这里以idea为例,配置VM options参数
参数格式为:-javaagent:/Agent的jar路径=参数
例如:
-javaagent:/Users/ityunqing/mycode/grouth/target/my-agent.jar=IT云清
项目启动后,就会看到,在main方法执行前,执行了premain方法。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。