使用固定agent
引入pom
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.4.16</version>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy-agent</artifactId>
<version>1.4.16</version>
</dependency>
实例
public static void installAgent(){
ByteBuddyAgent.install();
AgentBuilder agentBuilder = new AgentBuilder.Default()
.type(nameStartsWith("com.codecraft.demo")
.and(not(isInterface()))
.and(not(isStatic()))
.transform((builder,typeDescription,classLoader) -> builder
.method(ElementMatchers.any())
.intercept(MethodDelegation.to(TraceInterceptor.class)
);
agentBuilder.installOnByteBuddyAgent();
使用自己构建的agent
public static void premain(String argument, Instrumentation inst) {
System.out.println("start premain)");
new AgentBuilder.Default()
.type(nameStartsWith("com.codecraft.demo").and(not(isInterface())).and(not(isStatic())))
.transform((builder,typeDescription,classLoader) -> builder
.method(ElementMatchers.any())
.intercept(MethodDelegation.to(TraceInterceptor.class)
)
).with(new AgentBuilder.Listener(){
@Override
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule, DynamicType dynamicType) {
}
@Override
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule) {
}
@Override
public void onError(String s, ClassLoader classLoader, JavaModule javaModule, Throwable throwable) {
throwable.printStackTrace();
}
@Override
public void onComplete(String s, ClassLoader classLoader, JavaModule javaModule) {
}
})
.installOn(inst);
}
pom
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<!--<version>${maven.compiler}</version>-->
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<finalName>${project.artifactId}-${project.version}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<archive>
<manifestEntries>
<Premain-Class>${premain}</Premain-Class>
<Agent-Class>${premain}</Agent-Class>
</manifestEntries>
</archive>
</configuration>
<executions>
<execution>
<id>assemble-all</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
docs
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。