【问题标题】:Spring dependency injection - reflection / byte code instrumentationSpring依赖注入——反射/字节码检测
【发布时间】:2011-10-10 19:58:36
【问题描述】:

当我想将依赖注入与一些非​​默认构造函数一起使用时,即使用参数,spring 必须为此使用字节码检测,对吗?因为AFAIK反射只支持默认构造函数?

【问题讨论】:

    标签: spring dependencies code-injection


    【解决方案1】:

    Reflections 支持任意数量的参数,例如我有一个 TestClass 类,它在它的一个构造函数中接受两个参数:

    public TestClass(int test1, String test) {
        System.out.println(test1 + test);
    }
    

    我会通过反射调用这个构造函数,如下所示:

        Constructor<TestClass> constructor = TestClass.class.getConstructor(Integer.class, String.class);
        TestClass test = constructor.newInstance(1, "test");
    

    【讨论】:

      【解决方案2】:

      反射。

      请查看该类的源代码

      org.springframework.beans.factory.support.ConstructorResolver 方法:受保护的BeanWrapper autowireConstructor(...)

      调用 =>

      org.springframework.beans.factory.support.SimpleInstantiationStrategy 方法:public Object instantiate(...)

      调用 =>

      org.springframework.beans.BeanUtils 方法:public static Object instantiateClass(Constructor ctor, Object[] args)

      使用反射来创建 bean

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-23
        • 1970-01-01
        • 1970-01-01
        • 2017-09-04
        • 2018-11-21
        • 2012-12-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多