java - CGLib 代理和非空构造函数

标签 java spring jakarta-ee cglib

假设我有一些 A 类,它具有 B 类的属性。

public class ClassA{

private ClassB classB; 

public ClassA(ClassB classB){
 this.classB = classB;
}

 //some methods ommitted.
}

不,我有 CGLIB 代理:

public class CGLibProxy  implements MethodInterceptor{

    @Override
    public Object intercept(Object object, Method method, Object[] args,
            MethodProxy methodProxy) throws Throwable {

    if (method.getName().startsWith("print")){
        System.out.println("We will not run any method started with print"); 
        return null;
    }
        else
        return methodProxy.invokeSuper(object, args);
    }
}

现在,当我对 ClassA 使用 CGLib 时,代理会创建 ClassA 实例。

我的问题是如何将 classB 参数传递给此代理,因为据我了解 CGLib 将为 ClassA 运行空构造函数?

最佳答案

我没有看到任何关于如何使用 CGLibProxy 类包装 ClassA 的代码示例,但如果您直接处理 cglib,那么您应该有一个实例net.sf.cglib.proxy.Enhancer 在这种情况下,您可以按如下方式提供构造函数参数。

import net.sf.cglib.proxy.Enhancer;

public class CGLibProxyMain {

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(ClassA.class);
        enhancer.setCallback(new CGLibProxy());
        ClassA a = (ClassA) enhancer.create(new Class[] {ClassB.class}, new Object[] {new ClassB()});
        System.out.println(a.printB());;
        System.out.println(a.otherMethod());
    }
}

关于java - CGLib 代理和非空构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12887586/

相关文章:

java - Maven 配置文件在子模块中看不到依赖关系

Java - MySQL-StoredProcedure 未执行

java - Spring 3 : @Autowired dao fields are null in service beans with @Transactional annotation

java - 在 Spring Boot 中从 application.properties 配置国际化

java.lang.IllegalStateException : Failed to load ApplicationContext

spring - Spring MVC 中通过 REST 进行身份验证

java - Servlet 应用程序中没有加载任何属性文件

java - JSOUP 转换 html 行时缺少标签

java - 为什么我们需要 struts 中的 global-forwards 和 global-exceptions?

java - Spring中的UnsatisfiedDependencyException : Illegal arguments for constructor : argument type mismatch