`
jiaguwen123
  • 浏览: 410983 次
  • 性别: Icon_minigender_2
  • 来自: 深圳
社区版块
存档分类
最新评论

spring依赖注入原理

阅读更多

关于spring依赖注入原理的文章在网络上已经有很多,我要写的这篇文章原文出自http://taeky.iteye.com/blog/563450,只所以再一次写下来只是为了一为自己收藏,方便以后的复习;二是自己在用这个例子实践的时候遇到一些问题,自己记一下。另外这篇文章中用dom4j来解析spring的配置文件,我觉得也是个值得学习的地方。好了,不多说了,还是把代码再贴一下:
接口:PersonDao.java

package com.luojing.test.dao;

public interface PersonDao {
	
	public void add();

}


实现类:PersonDaoImp.java

package com.luojing.test.daoimp;

import com.luojing.test.dao.PersonDao;

public class PersonDaoImp implements PersonDao {

	public void add() {
		
		System.out.println("执行了add()方法!!!");
	}

}


服务接口:PersonService.java

package com.luojing.test.service;

public interface PersonService {
	
	public void save();

}


服务实现类:PersonServiceImp.java

package com.luojing.test.serviceimp;

import com.luojing.test.dao.PersonDao;
import com.luojing.test.service.PersonService;

public class PersonServiceImp implements PersonService {
	
	private PersonDao personDao;
	
	public PersonDao getPersonDao() {
		return personDao;
	}

    public void setPersonDao(PersonDao personDao) {
		this.personDao = personDao;
	}

    public void save() {
		
    	personDao.add();
    
	}

}


applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans   
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" >
           
<bean id="personDao" class="com.luojing.test.daoimp.PersonDaoImp"/>

<bean id="service" class="com.luojing.test.serviceimp.PersonServiceImp">

<property name="personDao" ref="personDao"></property>

</bean>

</beans>


创建bean,然后其属性用一集合存储在bean里BeanDefinition.java:

package com.luojing.test.testioc;

import java.util.ArrayList;
import java.util.List;

public class BeanDefinition {
	
	private String id;
	
	private String classname;
	
	private List<PropertyDefinition> propertys = new ArrayList<PropertyDefinition>();

	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 List<PropertyDefinition> getPropertys() {
		return propertys;
	}

	public void setPropertys(List<PropertyDefinition> propertys) {
		this.propertys = propertys;
	}
	
    public BeanDefinition(String id,String classname){
    	
    	this.id = id;
    	
    	this.classname = classname;
    }
}


属性bean PropertyDefinition.java:

package com.luojing.test.testioc;

public class PropertyDefinition {
	
	private String name;
	
	private String ref;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getRef() {
		return ref;
	}

	public void setRef(String ref) {
		this.ref = ref;
	}
	
	public PropertyDefinition(String name,String ref){
		
		this.name = name;
		
		this.ref = ref;
	}

}


解析spring配置文件并实例话bean ItcastClassPathXMLApplicationContext.java:

package com.luojing.test.testioc;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
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.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;

public class ItcastClassPathXMLApplicationContext {
	
	 private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();  
	 
	 private Map<String, Object> sigletons = new HashMap<String, Object>();  
	
	 public ItcastClassPathXMLApplicationContext(String filename){
		
		this.readXML(filename);
		this.instanceBeans();
		this.injectObject();
	}
	
	 /**  
     * 实现bean的实例化  
     */  
    private void instanceBeans() {   
        for (BeanDefinition beanDefinition : beanDefines) {   
            try {   
                if (beanDefinition.getClassname() != null && !"".equals(beanDefinition.getClassname().trim()))   
                    sigletons.put(beanDefinition.getId(), Class.forName(   
                            beanDefinition.getClassname()).newInstance());   
            } catch (Exception e) {   
                // 通过反射技术把bean都创建出来   
                e.printStackTrace();   
            }   
        }   
  
    } 
    /**  
     * 为bean对象的属性注入值  
     */  
    private void injectObject() {   
        for (BeanDefinition beanDefinition : beanDefines) {   
            Object bean = sigletons.get(beanDefinition.getId());   
            if (bean != null) {   
                try {   
                    PropertyDescriptor[] ps = Introspector.getBeanInfo(   
                            bean.getClass()).getPropertyDescriptors();   
                    //Introspector通过这个类可以取得bean的定义信息   
                    for (PropertyDefinition propertyDefinition : beanDefinition   
                            .getPropertys()) {   
                        for (PropertyDescriptor properdesc : ps) {  
           
                            if (propertyDefinition.getName().equals(properdesc.getName())) {   
                                Method setter = properdesc.getWriteMethod();// 获取属性的setter方法   
                                                                            // ,private   
                                if (setter != null) {//属性可能没有set方法,所以这里要判断一下   
                                    Object value = sigletons   
                                            .get(propertyDefinition.getRef());   
                                    setter.setAccessible(true);//如果set方法是私有的话,要设置它允许被访问   
                                    setter.invoke(bean, value);// 把引用对象注入到属性   
                                }   
                                break;   
                            }   
                        }   
                    }   
                } catch (Exception e) {   
                }   
            }   
        }   
    }   

	/**  
     * 读取xml配置文件  
     */  
    private void readXML(String filename) {   
        SAXReader saxReader = new SAXReader();   
        Document document = null;   
        try {   
            URL xmlpath = this.getClass().getClassLoader()   
                    .getResource(filename);   
            document = saxReader.read(xmlpath);   
            Map<String, String> nsMap = new HashMap<String, String>();   
            nsMap.put("ns", "http://www.springframework.org/schema/beans");// 加入命名空间   
            XPath xsub = document.createXPath("//ns:beans/ns:bean");// 创建beans/bean查询路径   
            xsub.setNamespaceURIs(nsMap);// 设置命名空间   
            List<Element> beans = xsub.selectNodes(document);// 获取文档下所有bean节点   
            for (Element element : beans) {   
                String id = element.attributeValue("id");// 获取id属性值   
                String clazz = element.attributeValue("class"); // 获取class属性值   
                System.out.println(id + " = " + clazz);
                BeanDefinition beanDefine = new BeanDefinition(id, clazz);   
                XPath propertysub = element.createXPath("ns:property");   
                propertysub.setNamespaceURIs(nsMap);// 设置命名空间   
                List<Element> propertys = propertysub.selectNodes(element);   
                for (Element property : propertys) {   
                    String propertyName = property.attributeValue("name");   
                    String propertyref = property.attributeValue("ref");   
                    System.out.println(propertyName + " = " + propertyref);   
                    PropertyDefinition propertyDefinition = new PropertyDefinition(   
                            propertyName, propertyref);   
                    beanDefine.getPropertys().add(propertyDefinition);   
                }   
                beanDefines.add(beanDefine);   
            }   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    }   
    
    /**  
     * 获取bean实例  
     */  
    public Object getBean(String beanName) {   
        return this.sigletons.get(beanName);   
    } 

}


测试类SpringTest.java:

package com.luojing.test.testioc;

import com.luojing.test.service.PersonService;

public class SpringTest {

	
	public static void main(String[] args) {
		
		 ItcastClassPathXMLApplicationContext ctx = new ItcastClassPathXMLApplicationContext("applicationContext.xml"); 
		 
		 PersonService ps = (PersonService)ctx.getBean("service");
			
		 ps.save();
	}

}


我在运行的过程中出现:java.lang.NoClassDefFoundError: org/jaxen/JaxenException弄了我好半天,后来在网上找出其原因是:除去必须有一个dom4j.jar外,还必须有一个jaxen-1.1.1.jar 文件,因为使用dom4j时调用了XPath,而没有在项目中加载jaxen-xx.xx.jar,jaxen是一个用Java开发的XPath 引擎,支持JDOM, dom4j。

分享到:
评论

相关推荐

    spring依赖注入的实现原理

    Spring依赖注入(Dependency Injection,简称DI)是Java应用开发中常用的设计模式,它极大地提高了代码的可测试性和可维护性。在Spring框架中,依赖注入是核心特性之一,通过控制反转(Inversion of Control,IoC)...

    Spring依赖注入原理解析.doc

    Spring依赖注入机制,也被称为控制反转(Inversion of Control,IOC),是Spring框架的核心特性,它使得应用程序的组件之间能够实现松散耦合。在传统编程中,对象通常自行创建和管理它们所依赖的其他对象,而在...

    Spring学习笔记(6)----编码剖析Spring依赖注入的原理

    本篇学习笔记将深入剖析Spring依赖注入的原理,通过源码分析帮助我们理解这一核心机制。 首先,依赖注入允许我们解耦组件之间的关系,使得各个组件可以独立地进行开发、测试和维护。在Spring中,DI主要通过两种方式...

    spring依赖注入原理与用法实例分析

    Spring 依赖注入原理与用法实例分析 Spring 依赖注入是 Spring 框架中的一种设计模式,它允许组件之间松散耦合,提高了系统的灵活性和可维护性。本文将详细介绍 Spring 依赖注入的原理与用法,通过实例分析,帮助...

    浅谈Spring IoC容器的依赖注入原理

    浅谈Spring IoC容器的依赖注入原理 Spring IoC容器的依赖注入原理是Spring框架的核心机制之一,负责将服务对象(Bean)实例化并将其提供给客户端使用。依赖注入原理可以分为两个阶段:IoC容器初始化和Bean实例化。 ...

    spring依赖注入三种方式 测试源码

    通过阅读和理解这些源码,你可以更深入地了解Spring依赖注入的工作原理及其在项目中的具体使用。 在进行依赖注入时,Spring使用BeanFactory或ApplicationContext作为容器,负责创建、管理和装配Bean。容器读取配置...

    Spring依赖注入检查.

    本文将深入探讨Spring依赖注入的概念、工作原理以及如何在实际项目中应用。 依赖注入(Dependency Injection,简称DI)是一种设计模式,它允许组件之间通过外部源来管理其依赖关系,而不是由组件自己来创建或查找...

    编码剖析Spring依赖注入的原理

    本文将深入解析Spring中的依赖注入原理,帮助开发者更好地理解和应用这一核心功能。 依赖注入(Dependency Injection,简称DI)是Spring框架的核心之一,它允许组件之间的依赖关系在运行时由外部容器来管理,而不是...

    Spring Ioc 注解 依赖注入

    ### Spring IoC与注解依赖注入详解 #### 一、Spring框架简介 Spring框架是由Rod Johnson创建的一个开源项目,最初是为了解决企业级应用开发中的复杂性问题而诞生的。Spring框架的核心特性包括IoC(Inversion of ...

    Spring依赖注入DI.zip

    下面我们将深入探讨Spring依赖注入的概念、工作原理以及如何在实践中应用。 1. **依赖注入概念**: - 依赖:一个类对另一个类的使用称为依赖。 - 注入:将依赖的对象传递给需要它的类,而不是由类自己去创建或...

    模拟spring依赖注入

    在Spring框架中,依赖注入(Dependency Injection,简称DI)是一种重要的设计模式,它极大地提高了代码的可测试性和可维护性。模拟Spring的依赖注入,旨在理解其核心机制,让我们一起深入探讨这一主题。 首先,我们...

    spring注入原理

    Spring框架是Java开发中不可或缺的一部分,它通过提供依赖注入(Dependency Injection,简称DI)和面向切面编程(Aspect-Oriented Programming,简称AOP)等核心功能,极大地简化了企业级应用的开发工作。...

    自己的代码模拟spring的依赖注入

    在IT行业中,Spring框架是Java开发中的一个基石,尤其在控制反转(IoC)和依赖注入(DI)方面。依赖注入是一种设计模式,它允许我们解耦组件,提高代码的可测试性和可维护性。Spring框架通过IoC容器来实现DI,让我们...

    springIoc实现原理

    在传统的软件设计中,对象的创建和依赖关系的维护通常由代码自身来完成,而在Spring Ioc中,这些控制权被反转给了Spring容器,使得对象的生命周期管理和依赖注入变得更为灵活和可扩展。 **一、控制反转(IoC)概念*...

    Spring读取配置文件原理(Spring如何依赖注入的)

    本文将深入探讨Spring如何通过读取配置文件实现依赖注入,并讲解相关源码,帮助理解其工作原理。 在Spring中,配置文件通常为XML格式,如`applicationContext.xml`,它定义了bean的实例化、属性设置、装配关系等。...

    spring课堂案例

    在"spring依赖注入原理"的案例中,我们可能会学习如何定义和使用这些注入方式,以及如何在实际项目中有效地管理和控制依赖关系。理解并熟练掌握依赖注入,不仅可以帮助我们编写更高质量的代码,还能使我们的应用程序...

    SSH笔记-泛型依赖注入

    在Spring 4版本中,泛型依赖注入是一项重要的特性,它极大地提高了代码的灵活性和可维护性。本笔记将深入探讨SSH中的Spring框架如何实现泛型依赖注入。 首先,我们来理解泛型的基本概念。泛型是Java SE 5引入的一种...

    详解Spring依赖注入:@Autowired,@Resource和@Inject区别与实现原理

    Spring 依赖注入:@Autowired,@Resource 和@Inject 区别与实现原理 Spring 依赖注入是指在应用程序中将对象之间的依赖关系自动装配的过程。Spring 框架提供了多种依赖注入方式,包括 @Autowired、@Resource 和@...

    spring 注入原理

    ### Spring注入原理详解 在Java开发领域,Spring框架无疑占据着举足轻重的地位,尤其在企业级应用中,Spring的依赖注入(Dependency Injection,DI)特性极大地简化了对象之间的依赖管理,使得代码更加模块化、可...

Global site tag (gtag.js) - Google Analytics