假設(shè)我想將 應(yīng)用于@Advice.OnMethodEnter中聲明的方法org.springframework.web.context.support.GenericWebApplicationContext。為此,我編寫了這個(gè)最小代理:public class SequenceAgent { public static void premain(final String args, final Instrumentation instrumentation) { new AgentBuilder.Default() .with(new AgentBuilder.InitializationStrategy.SelfInjection.Eager()) .type(nameStartsWith( "org.springframework.web.context.support.GenericWebApplicationContext")) .transform((builder, typeDescription, classLoader, module) -> builder .method(any()).intercept(Advice.to(SequenceAdvice.class))) .installOn(instrumentation); } public static class SequenceAdvice { @Advice.OnMethodEnter static void enter(@Advice.This Object thiz, @Advice.Origin Method method, @Advice.AllArguments Object... args) { String className = thiz.getClass().getName(); String methodName = method.getName(); System.out.println("Entered: " + className + "#" + methodName); } }}我希望此配置被過濾掉org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext,因?yàn)樗黄ヅ鋙rg.springframework.web.context.support.GenericWebApplicationContext,但看起來(lái)對(duì)此類對(duì)象的方法調(diào)用也被攔截:import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;public class AgentTest { public static void main(String[] args) { AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext(); context.containsBean("SomeBean"); }}當(dāng)附加到代理并運(yùn)行時(shí),它會(huì)打印出來(lái)(為了便于閱讀而包裝):Entered: org.springframework.boot.web.servlet.context. AnnotationConfigServletWebServerApplicationContext #getResourcePatternResolver...Entered: org.springframework.boot.web.servlet.context. AnnotationConfigServletWebServerApplicationContext #getResourceCache
1 回答

一只甜甜圈
TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超5個(gè)贊
字節(jié)好友使用 String.startsWith。
您所看到的是由于 Byte Buddy 檢測(cè)類,而不是實(shí)例。在某種程度上,想想 Byte Buddy 將通知代碼復(fù)制到目標(biāo)方法中。
結(jié)果,所有子類都會(huì)受到影響。為了做你正在做的事情,你需要在調(diào)用期間檢查實(shí)例類的類型,就像你想在 Java 中實(shí)現(xiàn)它一樣。
添加回答
舉報(bào)
0/150
提交
取消