springboot的@Autowired底层过程示例demo或者Apache commons-lang3实现

假设下面的类的属性被@Autowired注解

public class MyModel {

    private String test;

    public String getTest() {
        return test;
    }
}

下面是spring利用java的反射reflection注入属性

public class Test {
    public static void main(String[] args) {

        Class<?> clazz = MyModel.class;

        MyModel cc = null;
        try {
            cc = (MyModel) clazz.newInstance();
            Field f1 = cc.getClass().getDeclaredField("test");
            f1.setAccessible(true);
            f1.set(cc, "reflecting on life");
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }


        System.out.println(cc.getTest());

    }
}

或者Apache commons-lang3

//The "true" forces it to set, even with "private".
FieldUtils.writeField(childInstance, "a_field", "Hello", true);

猜你喜欢

转载自blog.csdn.net/c5113620/article/details/93718924