码迷,mamicode.com
首页 > 编程语言 > 详细

简单模拟spring依赖注入原理

时间:2018-07-13 13:17:09      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:exception   分享   cep   获取   java   iat   inf   set   实现   

接口:

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依赖注入原理

标签:exception   分享   cep   获取   java   iat   inf   set   实现   

原文地址:https://www.cnblogs.com/lshspace/p/9304260.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!