简单模拟spring依赖注入原理

Posted lshspace

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单模拟spring依赖注入原理相关的知识,希望对你有一定的参考价值。

接口:

package org.com.test.spring;

public interface PersonAction {
    
    public void sayHello();
    
}

 

实现类:

package org.com.test.spring;

public class PersonActionImpl implements PersonAction {

    @Override
    public void sayHello() {
        System.out.println("Hello!");

    }

}

 

方法Bean:

package org.com.test.spring;

public class ActionBean {
    
    PersonAction personAction;


    public void setPersonAction(PersonAction personAction) {
        this.personAction = personAction;
    }


    public void say() {
        personAction.sayHello();
    }
}

 

模拟测试类:

package org.com.test.spring;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class SpringTest {

    public static void main(String[] args)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException,
            SecurityException, IllegalArgumentException, InvocationTargetException {
        // 模拟spring注册bean
        Map<String, Object> map = new HashMap<>();
        map.put("actionBean", "org.com.test.spring.PersonActionImpl");
        // 模拟spring获取bean
        String beanName = (String) map.get("actionBean");
        Class<?> cls = Class.forName(beanName);
        Object object = cls.newInstance();
        // 模拟spring依赖注入,set方法
        ActionBean action = new ActionBean();
        Method method = action.getClass().getMethod("setPersonAction", PersonAction.class);
        method.invoke(action, object);
        // 模拟bean方法调用
        action.say();

    }
}

结果:

技术分享图片

 

以上是关于简单模拟spring依赖注入原理的主要内容,如果未能解决你的问题,请参考以下文章

spring练习,在Eclipse搭建的Spring开发环境中,使用set注入方式,实现对象的依赖关系,通过ClassPathXmlApplicationContext实体类获取Bean对象(代码片段

javaSpring 自己模拟 Spring 实现 IOC依赖注入 并且 解决 循环依赖

spring中依赖注入的原理

Spring 依赖注入原理

Spring第七弹—依赖注入之注解方式注入及编码解析@Resource原理

spring依赖注入使用的啥设计模式?