利用反射模拟spring

为了加深对spring的理解,我们手动模拟一下spring的实现.
自定义一个xml文件,放到resources目录下:

<beans>
    <bean id="userDao" class="com.dalingjia.spring.dao.impl.UserDaoImpl"></bean>

    <bean id="userService" class="com.dalingjia.spring.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>
</beans>

以下是User对象

package com.dalingjia.spring.bean;

public class User {
	private String username;
	private String password;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

然后是UserDao接口,以及它的实现类

package com.dalingjia.spring.dao;
import com.dalingjia.spring.bean.User;

public interface UserDao {

    public void add(User user);
}

package com.dalingjia.spring.dao.impl;
import com.dalingjia.spring.bean.User;
import com.dalingjia.spring.dao.UserDao;

public class UserDaoImpl implements UserDao {

    @Override
    public void add(User user) {
        System.out.println("a user add!");
    }
}

然后是UserService接口和实现类:

package com.dalingjia.spring.service;
import com.dalingjia.spring.bean.User;
public interface UserService {
    public void add(User user);
}

package com.dalingjia.spring.service.impl;
import com.dalingjia.spring.bean.User;
import com.dalingjia.spring.dao.UserDao;
import com.dalingjia.spring.service.UserService;
public class UserServiceImpl implements UserService {
    private UserDao userDao;
    public UserDao getUserDao() {
        return userDao;
    }
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    @Override
    public void add(User user) {
        userDao.add(user);
    }
}

然后我们利用jdom来解析xml文件:
利用反射将对象引用和对象放入map集合中,再利用反射将dao接口的实现类注入到service接口实现类的属性(set方法)中,下面代码需要引入jdom依赖:

<!-- https://mvnrepository.com/artifact/org.jdom/jdom -->
		<dependency>
			<groupId>org.jdom</groupId>
			<artifactId>jdom</artifactId>
			<version>2.0.2</version>
		</dependency>
package com.dalingjia.spring;

import org.apache.ibatis.javassist.tools.reflect.Sample;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.springframework.beans.BeansException;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;

public class ClassPathXmlAppliactionContext {
	
	private Map<Object,Object> beanMap = new HashMap<Object,Object>();
	
	public ClassPathXmlAppliactionContext(){
		SAXBuilder sb=new SAXBuilder();//解析xml的SAXBuiler对象
	    //构造文档对象 
	    Document doc = null;
		try {
			doc = sb.build(Sample.class.getClassLoader().getResourceAsStream("bean.xml"));
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
	    Element root=doc.getRootElement(); //获取根元素
	    List list=root.getChildren("bean");//取名字为bean的所有元素   
	    for(int i=0;i<list.size();i++){
	    	Element element=(Element)list.get(i);   
			String id=element.getAttributeValue("id"); //获取id  
			String clazz=element.getAttributeValue("class"); //获取class
			Object obj = null;
			try {
				//利用反射实例化对象
				obj = Class.forName(clazz).newInstance();
			} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
				e.printStackTrace();
			}
			beanMap.put(id, obj);//将对象放入beanMap中
			
			for (Element propertyElement : (List<Element>)element.getChildren("property")) {
				String name = propertyElement.getAttributeValue("name");//userDao
				String ref = propertyElement.getAttributeValue("ref");//userDao
				Object refObject = beanMap.get(ref);//userDaoImpl
				//方法名 setUserDao
				String methodName = "set"+name.substring(0, 1).toUpperCase()+name.substring(1);
				try {
					//获取方法,然后调用方法
					/* public class UserServiceImpl implements UserService
					 * refObject.getClass().getInterfaces()[0]:
					 * 返回的是UserDaoImpl类所实现的所有接口对象的一个数组,然后取第一个接口
					 * 获取的是UserService接口的Class对象
					 * 根据类中的方法名和方法的形参列表来获取方法
					 */
					Method method = obj.getClass().getMethod(methodName, refObject.getClass().getInterfaces()[0]);
					method.invoke(obj, refObject);//obj是方法所在的类对象,refObject是方法的形参列表(接口的实现类)
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
	    }
	}
	
	public Object getBean(String obj) throws BeansException {
		return beanMap.get(obj);
	}
}

根据类中的方法名和方法的形参列表来获取方法

/* public class UserServiceImpl implements UserService
 * refObject.getClass().getInterfaces()[0]:
 * 返回的是UserDaoImpl类所实现的所有接口对象的一个数组,然后取第一个接口
 * 获取的是UserService接口的Class对象
 */
Method method = obj.getClass().getMethod(methodName, refObject.getClass().getInterfaces()[0]);
//obj是方法所在的类对象,refObject是方法的形参列表(接口的实现类)
method.invoke(obj, refObject);

测试类:

package com.dalingjia.spring;

import com.dalingjia.spring.dao.UserDao;

public class SpringTest {

    public static void main(String[] args) {

        ClassPathXmlAppliactionContext classPathXmlAppliactionContext = new ClassPathXmlAppliactionContext();

        UserDao userDao = (UserDao) classPathXmlAppliactionContext.getBean("userDao");

        System.out.println(userDao);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值