模拟ClasspathXmlApplication:

package junit.test;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.commons.beanutils.ConvertUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader; public class ItcastClassPathXmlApplicationContext {
private ArrayList<BeanDefinition> beanDefinitions=new ArrayList<BeanDefinition>();
private Map<String,Object> sigletons=new HashMap<String,Object>(); public ItcastClassPathXmlApplicationContext(String filename){
this.readXml(filename);
this.instanceBeans();
this.annotationInject();
this.injectObject();
}
/**
* 注解方式装载对象
*/
private void annotationInject() {
for(String beanName :sigletons.keySet()){
Object bean=sigletons.get(beanName);
if(bean!=null){
try{
/*
* 查找方法上的注解
*/
PropertyDescriptor[] ps=Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();
for(PropertyDescriptor properdesc:ps){
Method setter=properdesc.getWriteMethod();
if(setter!=null && setter.isAnnotationPresent(ItcastResource.class)){
ItcastResource itcastResource=setter.getAnnotation(ItcastResource.class);
Object value=null;
if(itcastResource.name()!=null && !"".equals(itcastResource.name())){
value=sigletons.get(itcastResource.name());
}else{
value=sigletons.get(properdesc.getName());
if(value==null){
for(String key:sigletons.keySet()){
if(properdesc.getPropertyType().isAssignableFrom(sigletons.get(key).getClass())){
value=sigletons.get(key);
break;
}
}
}
}
setter.setAccessible(true);
setter.invoke(bean, value);
}
} /**
* 查找字段上的注解
*/
Field[] fields=bean.getClass().getDeclaredFields();
for(Field field:fields){
if(field.isAnnotationPresent(ItcastResource.class)){
ItcastResource resource=field.getAnnotation(ItcastResource.class);
Object value=null;
if(resource.name()!=null && !"".equals(resource.name())){
value=sigletons.get(resource.name());
}else{
value=sigletons.get(field.getName());
if(value==null){
for(String key:sigletons.keySet()){
if(field.getType().isAssignableFrom(sigletons.get(key).getClass())){
value=sigletons.get(key);
break;
}
}
}
}
String methodName="set"+field.getName().substring(,).toUpperCase()+field.getName().substring();
Method setter=bean.getClass().getMethod(methodName, field.getType());
setter.setAccessible(true);
setter.invoke(bean, value);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
} /**
* 为bean对象的属性注入值
*/
private void injectObject() {
for(BeanDefinition beanDefinition: beanDefinitions){
Object bean=sigletons.get(beanDefinition.getId());
if(bean!=null){
try {
PropertyDescriptor[] ps=Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();
for(PropertyDefinition propertyDefinition:beanDefinition.getPropertys()){
for(PropertyDescriptor properdesc:ps){
if(propertyDefinition.getName().equals(properdesc.getName())){
Method setter=properdesc.getWriteMethod();//获取属性的setter方法
if(setter!=null){
Object value=null;
if(propertyDefinition.getRef()!=null &&!"".equals(propertyDefinition.getRef())){
value=sigletons.get(propertyDefinition.getRef());
}else{
value=ConvertUtils.convert(propertyDefinition.getValue(), properdesc.getPropertyType());
}
setter.setAccessible(true);
setter.invoke(bean, value); }
break; }
}
}
} catch (Exception e) {
e.printStackTrace();
} }
}
}
/**
* 完成bean的实例化
*/
private void instanceBeans(){
for(BeanDefinition bd:beanDefinitions){
try {
if(bd.getClassName()!=null && !"".equals(bd.getClassName().trim()))
sigletons.put(bd.getId(), Class.forName(bd.getClassName()).newInstance());
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 解析xml文件
* @param fileName
*/
private void readXml(String fileName) {
File inputXml=new File(fileName);
URL url=this.getClass().getClassLoader().getResource(fileName);
SAXReader saxReader=new SAXReader();
try {
Document document=saxReader.read(url);
Element root=document.getRootElement();
@SuppressWarnings("unchecked")
List<Element> beans=root.elements("bean"); for(Element bean:beans){
String id= bean.attributeValue("id");
String className=bean.attributeValue("class");
BeanDefinition bd=new BeanDefinition(id,className);
@SuppressWarnings("unchecked")
List<Element> propertys=bean.elements("property");
for(Element property:propertys){
String propertyName = property.attributeValue("name");
String propertyRef = property.attributeValue("ref");
String propertyValue=property.attributeValue("value");
PropertyDefinition pd=new PropertyDefinition(propertyName, propertyRef,propertyValue);
bd.getPropertys().add(pd);
}
beanDefinitions.add(bd);
} } catch (DocumentException e) {
e.printStackTrace();
}
} public Object getBean(String beanName){
return this.sigletons.get(beanName);
}
}

存放bean信息的类:

package junit.test;

import java.util.ArrayList;
import java.util.List; /**
* 存放读取到的bean的信息
* @author Administrator
*
*/
public class BeanDefinition {
private String id;
private String className;
private List<PropertyDefinition> propertys=new ArrayList<PropertyDefinition>(); public BeanDefinition() {
super();
} public BeanDefinition(String id, String className) {
super();
this.id = id;
this.className = className;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
} public void setPropertys(List<PropertyDefinition> propertys) {
this.propertys = propertys;
} public List<PropertyDefinition> getPropertys() {
return propertys;
} }

存放bean中属性信息的类:

package junit.test;
/**
* 属性的定义类
* @author Administrator
*
*/
public class PropertyDefinition { private String name;
private String ref;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PropertyDefinition(String name, String ref,String value) {
super();
this.name = name;
this.ref = ref;
this.value=value;
}
public PropertyDefinition() {
super();
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
} }

对应Resource注解:

package junit.test;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.METHOD})
public @interface ItcastResource {
public String name() default "";
}

spring框架IOC原理分析代码的更多相关文章

  1. Spring之IOC原理及代码详解

    一.什么是IOC 引用 Spring 官方原文:This chapter covers the Spring Framework implementation of the Inversion of ...

  2. Spring框架的反序列化远程代码执行漏洞分析(转)

    欢迎和大家交流技术相关问题: 邮箱: jiangxinnju@163.com 博客园地址: http://www.cnblogs.com/jiangxinnju GitHub地址: https://g ...

  3. Spring的IOC原理[通俗解释一下]

    Spring的IOC原理[通俗解释一下] 1. IoC理论的背景我们都知道,在采用面向对象方法设计的软件系统中,它的底层实现都是由N个对象组成的,所有的对象通过彼此的合作,最终实现系统的业务逻辑. 图 ...

  4. Spring依赖注入原理分析

    在分析原理之前我们先回顾下依赖注入的概念: 我们常提起的依赖注入(Dependency Injection)和控制反转(Inversion of Control)是同一个概念.具体含义是:当某个角色( ...

  5. Spring框架IOC容器和AOP解析 非常 有用

    Spring框架IOC容器和AOP解析   主要分析点: 一.Spring开源框架的简介  二.Spring下IOC容器和DI(依赖注入Dependency injection) 三.Spring下面 ...

  6. Shiro框架 (原理分析与简单实现)

    Shiro框架(原理分析与简单实现) 有兴趣的同学也可以阅读我之前分享的:Java权限管理(授权与认证)CRM权限管理   (PS : 这篇博客里面的实现方式没有使用框架,完全是手写的授权与认证,可以 ...

  7. 自己动手写Spring框架--IOC、MVC

    对于一名Java开发人员,我相信没有人不知道 Spring 框架,而且也能够轻松就说出 Spring 的特性-- IOC.MVC.AOP.ORM(batis). 下面我想简单介绍一下我写的轻量级的 S ...

  8. Spring IOC原理分析

    IOC IOC(Inversion of Control)控制反转:所谓的控制反转,就是把原先需要我们代码自己实现对象的创建和依赖,反转给容器来实现.那么必然Spring需要创建一个容器,同时需要创建 ...

  9. Spring框架IOC容器和AOP解析

    主要分析点: 一.Spring开源框架的简介  二.Spring下IOC容器和DI(依赖注入Dependency injection) 三.Spring下面向切面编程(AOP)和事务管理配置  一.S ...

随机推荐

  1. GroupBox与Panel控件

    1.GroupBox控件常常用于逻辑地组合一组控件,如RadioButton 及 CheckBox控件,显示一个框架,其上有一个标题. 2.Panel 可以包含多个控件,以便将这些控件编为一组,以便方 ...

  2. ORA-02050故障诊断一例

    http://czmmiao.iteye.com/blog/1474678昨天客户反映说在下午某时间段有几个事务失败了,让我查下当时数据库系统的负载是否正常,看了下CPU的历史负载,很正常,于是看了下 ...

  3. springboot输出日志到指定目录,简单粗暴,springboot输出mybatis日志

    springboot官方文档地址https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot- ...

  4. php nginx超时出错

    执行PHP操作大文件insert mysql数据库时,出现这个错误提示 The page you are looking for is temporarily unavailable.Please t ...

  5. Go 语言从新手到大神:每个人都会踩的五十个坑(转)

    Go语言是一个简单却蕴含深意的语言.但是,即便号称是最简单的C语言,都能总结出一本<C陷阱与缺陷>,更何况Go语言呢.Go语言中的许多坑其实并不是因为Go自身的问题.一些错误你再别的语言中 ...

  6. JQ动态获取数据

    转:JQUERY获取浏览器窗口的高度和宽度 June 27, 2012 <script type="text/javascript"> $(document).read ...

  7. ASP.NET动态网站制作(6)-- JS(1)

    前言:JS的第一节课,在Visual Studio 2013中编写及运行.新建项目->Web->ASP.NET Web应用程序->Empty,打开后在项目下添加新建css文件夹和js ...

  8. centOS7 安装nginx+php+mysql

    nginx安装 本文是介绍使用源码编译安装,包括具体的编译参数信息. 正式开始前,编译环境gcc g++ 开发库之类的需要提前装好. 安装make: yum -y install gcc automa ...

  9. FPGA学习笔记之Altera FPGA使用JIC文件配置固化教程(转)

    很多做过单片机的朋友都知 道,我们在对MCU烧写完程序固件后,那么该程序固件就存储在了该MCU内部.即使MCU断电了再重新上电,程序也能继续运行.这是因为对MCU烧写固件 的实质就是将程序固件写入到M ...

  10. COGS1532. [IOI2001]移动电话

    1532. [IOI2001]移动电话 ★☆   输入文件:mobilephones.in   输出文件:mobilephones.out   简单对比时间限制:5 s   内存限制:256 MB [ ...