Java代码解析xml文件和spring中的注解(详细代码说明)

解析xml

1.导包
在这里插入图片描述
2.写xml文件

emp.xml

<?xml version="1.0" encoding="UTF-8"?>
<emps>
    <!--属性  -->
	<emp id="0001">
	    <!-- 文本节点 -->
		<name>张三</name>
		<age>18</age>
		<salary>8000</salary>
	</emp>
	<emp id="0002">
		<name>李四</name>
		<age>13</age>
		<salary>98000</salary>
	</emp>
</emps>

3.创建类

public class Emp implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = -7300737128592933710L;
	private String id;
	private String name;
	private int age;
	private int salary;
	public Emp() {
		
	}
	public Emp(String id, String name, int age, int salary) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.salary = salary;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public int getSalary() {
		return salary;
	}
	public void setSalary(int salary) {
		this.salary = salary;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + salary;
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Emp other = (Emp) obj;
		if (age != other.age)
			return false;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (salary != other.salary)
			return false;
		return true;
	}
	@Override
	public String toString() {
		return "Emp [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + "]";
	}
}

4.解析xml的类

public class ReadXml {
	public static void main(String[] args) throws Exception {
		List<Emp> empList=new ArrayList<>();
		
		//1.确定输入流
		SAXReader reader=new SAXReader();
		//2.获取Document对象
		Document document=reader.read(new File("config/emp.xml"));
		//3.获取根节点
		Element rootElement=document.getRootElement();
		System.out.println(rootElement.getName());  //emps
		//4.使用迭代器迭代emps节点下的子节点
		Iterator<Element> it=rootElement.elementIterator();
		while(it.hasNext()) {
			Emp emp=new Emp();
			
			//<emp id="0001">
			Element element=it.next();
			System.out.println(element.getName());  //emp
			//5.获取属性节点attribute("id"),获取节点属性值getValue()
			//String id=element.attribute("id").getValue();
			//System.out.println(id);
			System.out.println(element.attributeValue("id"));  //0001
			emp.setId(element.attributeValue("id"));
			//6.迭代emp节点下的子节点
			Iterator<Element> it2=element.elementIterator();
			while(it2.hasNext()) {
				//<emp id="0001">
				Element element2=it2.next();
				System.out.println("\t"+element2.getName());
				//getText()获取节点的值(文本节点)
				System.out.println("\t"+element2.getText());
				if(element2.getName().equals("name")) {
					emp.setName(element2.getText());
				}
				if(element2.getName().equals("age")) {
					emp.setAge(Integer.parseInt(element2.getText()));
				}
				if(element2.getName().equals("salary")) {
					emp.setSalary(Integer.parseInt(element2.getText()));
				}
			}
			empList.add(emp);
		}
		System.out.println(empList);
	}
}

运行结果:

emps
emp
0001
	name
	张三
	age
	18
	salary
	8000
emp
0002
	name
	李四
	age
	13
	salary
	98000
[Emp [id=0001, name=张三, age=18, salary=8000], Emp [id=0002, name=李四, age=13, salary=98000]]

了解:通过类写一个xml文件

public class WriteXml {

	public static void main(String[] args) throws Exception{
		//1.准备数据
		List<Emp> list=new ArrayList<>();
		list.add(new Emp("0001","admin1",20,7000));
		list.add(new Emp("0002","admin2",18,8000));
		//1.Document对象
		Document document=DocumentHelper.createDocument();
		//2.Document对象中添加element
		//添加根节点<emps>
		Element rootElement=document.addElement("emps");
		//添加emp节点,根据list集合元素的个数
		for(Emp emp:list) {
			Element empElement=rootElement.addElement("emp");
			empElement.addAttribute("id",emp.getId());
			Element nameElement=empElement.addElement("name");
			nameElement.addText(emp.getName());
			Element ageElement=empElement.addElement("age");
			ageElement.addText(emp.getAge()+"");
			Element salaryElement=empElement.addElement("salary");
			salaryElement.addText(emp.getSalary()+"");
		}
		
		//3.输出流把Document对象写到数据文件
		XMLWriter writer=new XMLWriter(new FileOutputStream("config/emp2.xml"),OutputFormat.createCompactFormat());
		writer.write(document);
		writer.close();

	}

}

练习1:

EmpDao.java

public class EmpDao {
	public void insert() {
		System.out.println("添加emp数据");
	}

}

EmpService.java

public class EmpService {
	private EmpDao empDao1;
	public void addEmp() {
		empDao1.insert();
	}

}

bean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans>
	<bean id="empDao" class="day_19_xml_zhujie.EmpDao"></bean>
	<bean id="empService" class="day_19_xml_zhujie.EmpService">
		<property name="empDao1" ref="empDao"></property>
	</bean>
</beans>

通过反射创建对象,给成员变量赋值的工具类(IOC容器):

//通过反射创建对象,给成员变量赋值的工具类(创建对象的容器)
public class BeanFactory {
	private static Map<String,Object> map=new HashMap<>();
	static {
		try {
			init();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void init() throws Exception {
		//1.解析xml文件
		SAXReader reader=new SAXReader();
		Document document=reader.read(new File("config/bean.xml"));
		Element rootElement=document.getRootElement();
		Iterator<Element> it=rootElement.elementIterator();
		while(it.hasNext()) {
			Element element=it.next();
			String id=element.attributeValue("id");
			String className=element.attributeValue("class");
			System.out.println(id+","+className);
			//2.通过反射创建两个对象
			Class<?> clazz=Class.forName(className);
			Object obj=clazz.newInstance();
			//3.设置到map集合
			map.put(id, obj);
			//4.给service类的属性赋值
			Iterator<Element> it2=element.elementIterator();
			while(it2.hasNext()) {
				Element element2=it2.next();
				String name=element2.attributeValue("name");
				String ref=element2.attributeValue("ref");
				Field f=clazz.getDeclaredField(name);
				f.setAccessible(true);
				f.set(obj, map.get(ref));
			}
		}
	}
	
   //提供给外界的接口
	public static Object getBean(String key) {
		//返回map集合key的值
		return map.get(key);
	}
	public static void main(String[] args) throws Exception {
		BeanFactory bean=new BeanFactory();
		EmpService s=(EmpService) bean.getBean("empService");
		s.addEmp();
	}

}

运行结果:

empDao,day_19_xml_zhujie.EmpDao
empService,day_19_xml_zhujie.EmpService
添加emp数据

练习2:

public class Student {
	public String study(String str) {
		return str;
	}

}
public class Teacher {
	private Student stu;
	private String name;
	public void teacher() {
		System.out.println(name+"教大家学习"+stu.study("java"));
	}

}

beanStu.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans>
	<bean id="stu12" class="day_19_xml_zhujie.Student"></bean>
	<bean id="teacher" class="day_19_xml_zhujie.Teacher">
	    <property name="name" value="王老师"></property>
		<property name="stu" ref="stu12"></property>
	</bean>
</beans>
public class BeanFactoryTest {
	private static Map<String,Object> map=new HashMap<>();
	static {
		try {
			init();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void init() throws Exception {
		//1.解析xml文件
		SAXReader reader=new SAXReader();
		Document document=reader.read(new File("config/beanStu.xml"));
		Element rootElement=document.getRootElement();
		Iterator<Element> it=rootElement.elementIterator();
		while(it.hasNext()) {
			Element element=it.next();
			String id=element.attributeValue("id");
			String className=element.attributeValue("class");
			System.out.println(id+","+className);
			//2.通过反射创建两个对象
			Class<?> clazz=Class.forName(className);
			Object obj=clazz.newInstance();
			//3.设置到map集合
			map.put(id, obj);
			//4.给service类的属性赋值
			Iterator<Element> it2=element.elementIterator();
			while(it2.hasNext()) {
				Element element2=it2.next();
				String name=element2.attributeValue("name");
				Field f=clazz.getDeclaredField(name);
				f.setAccessible(true);
				if(element2.attribute("value")!=null) {
					String value=element2.attribute("value").getValue();
					f.set(obj, value);
				}
				if(element2.attribute("ref")!=null) {
					String ref=element2.attributeValue("ref");
					f.set(obj, map.get(ref));
				}
			}
		}

	}
	//提供给外界的接口
	public static Object getBean(String key) {
		//返回map集合key的值
		return map.get(key);
	}
	public static void main(String[] args) throws Exception {
		BeanFactoryTest bean=new BeanFactoryTest();
		Teacher t=(Teacher) bean.getBean("teacher");
		t.teacher();

	}

}

运行结果:

stu12,day_19_xml_zhujie.Student
teacher,day_19_xml_zhujie.Teacher
王老师教大家学习java

解析注解

注解

 java中元注解(用来标识注解的注解)有四个: 
     @Target @Retention  @Document @Inherited;

 @Target:注解的作用目标       
     @Target(ElementType.TYPE)   
     可以作用在接口、类、枚举、注解
     @Target(ElementType.FIELD) 
     字段、枚举的常量
     @Target(ElementType.METHOD) 
     方法
     @Target(ElementType.PARAMETER) 
     方法参数
	 @Target(ElementType.CONSTRUCTOR)  
     构造函数
     @Target(ElementType.LOCAL_VARIABLE)
     局部变量
     @Target(ElementType.ANNOTATION_TYPE)
 	 注解
     @Target(ElementType.PACKAGE) 
     包  

==================================================

 @Retention:注解的保留位置         
     @Retention(RetentionPolicy.SOURCE)   
     注解仅存在于源码中,在class字节码文件中不包含  
     @Retention(RetentionPolicy.CLASS)      
     默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
     @Retention(RetentionPolicy.RUNTIME)  
     注解会在class字节码文件中存在,在运行时可以通过反射获取到

 @Document:说明该注解将被包含在javadoc中
 @Inherited:说明子类可以继承父类中的该注解

@Bean(id="aaa")
public class Demo {
	@Property(value="admin")
	private String name;
}

@Bean(id="a")
class A{
	@Property(ref="aaa")
	private Demo demo;
}

定义注解

//定义注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Bean {
	public String id();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Property {
	public String value() default "";
	public String ref() default "";

}
public class TestAnnotation {

	public static void main(String[] args) throws Exception {
		Map<String,Object> map=new HashMap<>();
		Class<Demo> clazz=Demo.class;
		if(clazz.isAnnotationPresent(Bean.class)) {
			Bean bean=clazz.getAnnotation(Bean.class);
			String id=bean.id();
			System.out.println(id);   //aaa
			//map.put(id, clazz.newInstance());
		}
		Field f=clazz.getDeclaredField("name");
		f.setAccessible(true);
		if(f.isAnnotationPresent(Property.class)) {
			Property property=f.getAnnotation(Property.class);
			String a=property.ref();
			String b=property.value();
			System.out.println(a+","+b);   //,admin
			//map.put(id, clazz.newInstance());
		}	

	}

}

如果一个注解可以在多个目标上使用可以定义为(枚举类型)
value可以省略


练习:将包下的所有含有Bean注解的类解析

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Bean {
	public String id();

}
@Bean(id="empDao")
public class EmpDao {
	public void insert() {
		System.out.println("empDao");
	}

}
@Bean(id="empService")
public class EmpService {

}

testAnnotation.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans>
<context-scan package="day_20.annotation"/>
</beans>
public class BeanFactory {
	private static Map<String,Object> map=new HashMap<>();
	static {
		try {
			init();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@SuppressWarnings("deprecation")
	public static void init() throws Exception  {
		//Class<?> clazz=EmpDao.class;

		SAXReader reader=new SAXReader();
		Document document=reader.read(new File("config/testAnnotation.xml"));
		Element root=document.getRootElement();
		Element e=root.element("context-scan");
		String packageName=e.attributeValue("package");
		String path=System.getProperty("user.dir")+"\\src\\"+packageName.replace(".", "\\");
		File file=new File(path);
		File[] files=file.listFiles();
		for(File f:files) {
			if(f.isFile()) {
				String fileName=f.getName().substring(0,f.getName().indexOf("."));
				String className=packageName+"."+fileName;
				Class<?> clazz=Class.forName(className);
				if(clazz.isAnnotationPresent(Bean.class)) {
					Bean bean=(Bean) clazz.getAnnotation(Bean.class);
					String id=bean.id();
					map.put(id, clazz.newInstance());
				}
			}
		}


	}
	public static Object getBean(String key) {
		//返回map集合key的值
		return map.get(key);
	}
	public static void main(String[] args) {
		System.out.println(map);
	}

}

运行结果:

{empService=day_20.annotation.EmpService@694e1548, empDao=day_20.annotation.EmpDao@1c3a4799}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值