手写LCSpring(3),注解自动注入

本文介绍如何手写LCSpring框架,并重点讲解如何实现注解自动注入的功能,从XML配置到注解的使用,以及核心类的实现和POJO类的设计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 LcSpring3.xml配置文件

<LcSpring>

	<bean id="s1" classname="com.java.zlcZhujie.Student">
	   <property name="rollno">9527</property>
	   <property name="firstname">卧龙</property>
	   <property name="marks">85</property>
	   <!-- <property name="teacher" ref="true">t1</property> -->
	</bean>
	
	<bean id="t1" classname="com.java.zlcZhujie.Teacher">
	   <property name="id">12</property>
	   <property name="name">水镜先生</property>
	</bean>

</LcSpring>

注解

package com.java.zlcZhujie;
 
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
 
@Retention(RetentionPolicy.RUNTIME)
public @interface LcAutowired {
 
}

 获取bean核心类

package com.java.zlcZhujie;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class LcSpring {
	public static void main(String[] args) throws Exception {
		LcSpring lcSpring=new LcSpring();
		Student student=(Student) lcSpring.getBean("s1");
		System.out.println(student);	
	}
	
	/**
	 * 根据id获取bean
	 * @param id
	 * @return
	 */
	public Object getBean(String id) {
		String classname = "";
		Object object = null;
		Map map = new HashMap();
		try {
			File inputFile = new File("LcSpring3.xml");
			// 1.create DocumentBuilder object
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			// 2.create Document object
			Document doc = dBuilder.parse(inputFile);
			doc.getDocumentElement().normalize();
			// get root node
			// Node node=doc.getFirstChild();
			String nameString = doc.getFirstChild().getNodeName();
			if (!nameString.equals("LcSpring")) {
				throw new Exception("未发现LcSpring");
			}
			NodeList nodeList = doc.getElementsByTagName("bean");
			for (int i = 0; i < nodeList.getLength(); i++) {
				//获得一级子元素
		        Element element = (Element)nodeList.item(i);
		        //获得属性
		        String beanid = element.getAttribute("id");
		        //获得元素的值
		        String name = element.getFirstChild().getNodeValue();
		       
		        if(id.equals(beanid)){
		        	classname = element.getAttribute("classname");		        	
		        	NodeList propertyNodeList = element.getElementsByTagName("property");
		        	for (int j = 0;j < propertyNodeList.getLength(); j++) {		    
		        		String ref = ((Element) propertyNodeList.item(j)).getAttribute("ref");
						Object value = "";
						if (ref.equals("true")) {
							value = getBean(propertyNodeList.item(j).getTextContent());
						} else {
							value = propertyNodeList.item(j).getTextContent();
						}

						String property = ((Element) propertyNodeList.item(j)).getAttribute("name");
						map.put(property, value);
		        	}
		        	
		        	List list=getFieldAnnotation(Class.forName(classname),LcAutowired.class);
		    		for (Object fieldobject : list) {
		    			Object annoObject=getBeanByClassName(((Field)fieldobject).getType().getName());
		    			map.put(((Field)fieldobject).getName(),annoObject);
		    		}
		        }
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			object = Class.forName(classname).getConstructor().newInstance();
			object = setValue(object, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}

	public Object setValue(Object object, Map map) {
		try {
			for (Object key : map.keySet()) {
				Object value = map.get(key);
				Field f1 = object.getClass().getDeclaredField((String) key);
				f1.setAccessible(true);
				String type = f1.getType().toString();// 得到此属性的类型
				if (type.endsWith("int") || type.endsWith("Integer")) {
					f1.set(object, Integer.parseInt((String) value));
				} else {
					f1.set(object, value);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}
	
	/**
	 * 查找类的所有属性是否含有某注解
	 * @param objClazz  类对象
	 * @param annoClazz  注解类对象
	 * @return 含有该注解的属性列表
	 */
	@SuppressWarnings({ "rawtypes",  "unchecked" })
	public List getFieldAnnotation(Class objClazz,Class annoClazz){
		Field[] fields =objClazz.getDeclaredFields();
		List list=new ArrayList();
		for (Field field : fields) {
			if(field.getAnnotation(annoClazz)!=null){
				list.add(field);
			}
		}
		return list;
	}
	
	/**
	 * 通过类全名查找生成类对象
	 * @param className
	 * @return
	 */
	public Object getBeanByClassName(String className){		
		File inputFile = new File("LcSpring3.xml");
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		Document doc =null;
		try {
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			doc =  dBuilder.parse(inputFile);
		
			doc.getDocumentElement().normalize();
			String nameString = doc.getFirstChild().getNodeName();
			if (!nameString.equals("LcSpring")) {
				throw new Exception("未发现LcSpring");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		NodeList nodeList = doc.getElementsByTagName("bean");
		for (int i = 0; i < nodeList.getLength(); i++) {
			//获得一级子元素
	        Element element = (Element)nodeList.item(i);
	        //获得属性
	        String classname = element.getAttribute("classname");
	        if(classname.equals(className)){
	        	String id=element.getAttribute("id");
	        	Object object=getBean(id);
	        	return object;
	        }
		}
		return null;
	}
}

pojo类

package com.java.zlcZhujie;

public class Student {
	private int rollno;
	private String firstname;
	private String marks;
	@LcAutowired
	private Teacher teacher;
	
	@Override
	public String toString() {
		return "Student [rollno=" + rollno + ", firstname=" + firstname + ", marks=" + marks + ", teacher=" + teacher
				+ "]";
	}
}



package com.java.zlcZhujie;

public class Teacher {
	private int id;
	private String name;
	@Override
	public String toString() {
		return "Teacher [id=" + id + ", name=" + name + "]";
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值