我試圖攔截與@Inject
註釋構造函數。在小單元測試的情況下,這很好。但是,在像Spring這樣的DI容器的情況下,它會以ClassNotFoundException
失敗。攔截的構造導致ClassNotFoundException的
我設法縮小的根本原因。在儀表類上調用getDeclaredConstructors
將觸發此異常。有趣的是,如果我們首先創建該類的一個實例,問題就會消失。
例如:
public class InterceptConstructorTest {
@Test
public void testConstructorInterception() throws ClassNotFoundException {
ByteBuddyAgent.install();
new AgentBuilder.Default().type(nameStartsWith("test")).transform(new AgentBuilder.Transformer() {
@Override
public Builder<?> transform(Builder<?> builder, TypeDescription td) {
return builder.constructor(isAnnotatedWith(Inject.class))
.intercept(SuperMethodCall.INSTANCE.andThen(MethodDelegation.to(ConstructorInterceptor.class)));
}
}).installOnByteBuddyAgent();
// If this line is uncommented, ClassNotFoundException won't be thrown
// MyClass myClass = new MyClass("a param");
// Manually load MyClass
Class<?> myClassDefinition = getClass().getClassLoader().loadClass("test.MyClass");
// Throws NoClassDefFoundError
for(Constructor<?> constructor : myClassDefinition.getDeclaredConstructors()) {
System.out.println(constructor);
}
}
}
堆棧堆棧跟蹤,可以發現:http://pastebin.com/1zhx3fVX
class MyClass {
@Inject
public MyClass(String aParam) {
System.out.println("constructor called");
}
}
class ConstructorInterceptor {
public static void intercept() {
System.out.println("Intercepted");
}
}
自0.7.7版本,字節巴迪的新的默認'InitiailizationStrategy'需要照顧的問題給你。新版本目前與Maven Central Repository同步。 –
在移至0.7.7之後,我的應用程序過早退出,執行'main'之前。沒有例外被提出。任何想法,我可以如何幫助你找出這個問題? – user3408654
即使儀器失效,也不應該發生這種情況。您可以隨時添加'AgentBuilder.Listener'來檢查Byte Buddy是否發出錯誤。也許您的代理仍在使用老版本的Byte Buddy導致'NoClassDefFoundError'?你的單元測試是否適用於新版本?如果是這樣,我認爲你有一個版本衝突的地方。 –