java的反射机制+Dom4j 实现Spring IOC的原理

16 篇文章 0 订阅
4 篇文章 0 订阅
本文探讨了如何使用Java的反射机制和Dom4j库来理解Spring框架中的控制反转(IOC)原理。通过分析测试工程的目录结构,包括pom.xml配置文件,User.java实体类,以及应用配置文件application.xml,阐述了Spring如何通过自定义的ClassPathXmlApplicationContext类来改变传统获取bean对象的方式。
摘要由CSDN通过智能技术生成

测试工程的目录结构

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>spring-ioc</groupId>
  <artifactId>spring-ioc</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <dependencies>
		<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.4</version>
		</dependency>
		<dependency>
			<groupId>org.dom4j</groupId>
			<artifactId>dom4j</artifactId>
			<version>2.0.0</version>
		</dependency>
	</dependencies>
</project>

User.java

package com.sunj.entity;

import java.util.List;

public class User {
	private String id;
	private String name;
	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;
	}
	
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + "]";
	}
	public User(String id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	public User() {
		super();
	}
	
	
}

spring的配置文件application.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="    
     http://www.springframework.org/schema/beans     
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
     http://www.springframework.org/schema/tx     
     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd    
     http://www.springframework.org/schema/aop     
     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd    
     http://www.springframework.org/schema/context    
     http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<bean id="user1" class="com.sunj.entity.User">
		<property name="id" value="0001"></property>
		<property name="name" value="张三"></property>
	</bean>
	<bean id="user2" class="com.sunj.entity.User">
		<property name="id" value="0002"></property>
		<property name="name" value="李四"></property>
	</bean>
</beans>

位重写ClassPathXmlApplicationContext类之前,spring获取bean对象是这样的

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
	public static void main(String[] args) {
		//读取spring配置
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
		User user = (User) context.getBean("user1");
		System.out.println(user);
		User user2 = (User) context.getBean("user2");
		System.out.println(user2);
	}
}

重新的ClassPathXmlApplicationContext类

package com.sunj.test;

import java.lang.reflect.Field;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.sunj.entity.User;

public class ClassPathXmlApplicationContext {
	private String path;
	private static final String ID = "id";
	private static final String CLASS = "class";
	private static final String NAME = "name";
	private static final String VALUE = "value";
	
	
	public ClassPathXmlApplicationContext(String path) {
		super();
		this.path = path;
	}
	
	public Object getBean(String beanId) throws DocumentException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException{
		//1、解析xml
		SAXReader saxreader = new SAXReader();
		Document read = saxreader.read(this.getClass().getClassLoader().getResource(this.path));
		Element rootElement = read.getRootElement();
		List<Element> elements = rootElement.elements();
		for (Element element : elements) {
			if(StringUtils.isBlank(element.attributeValue(this.ID))){
				System.out.println("你找的类不存在");
				return null;
			}
			//2、使用bean的id查找对应xml节点,获取class节点属性
			String pro = element.attributeValue(this.ID);
			if(!beanId.equals(pro)){
				continue;
			}
			
			String classValue = element.attributeValue(this.CLASS);
			if(StringUtils.isBlank(classValue)){
				return null;
			}
			//3、使用java的反射机制初始化类
			Class forName = Class.forName(classValue);
			Object instance = forName.newInstance();
			List<Element> sunElements = element.elements();
			//使用java的反射机制给私有属性赋值
			for (Element element2 : sunElements) {
				String nameV = element2.attributeValue(this.NAME);
				String valueV = element2.attributeValue(this.VALUE);
				Field field = forName.getDeclaredField(nameV);
				field.setAccessible(true);
				field.set(instance, valueV);
			}
			return instance;
			
		}
		return null;
	}
	
	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, DocumentException {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
		User user = (User) context.getBean("user2");
		System.out.println(user);
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值