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

Java代码

  1. package com.luojing.test.dao;

  2. public interface PersonDao {

  3. public void add();

  4. }

实现类:PersonDaoImp.java

Java代码

  1. package com.luojing.test.daoimp;

  2. import com.luojing.test.dao.PersonDao;

  3. public class PersonDaoImp implements PersonDao {

  4. public void add() {

  5. System.out.println("执行了add()方法!!!");

  6. }

  7. }

服务接口:PersonService.java

Java代码

  1. package com.luojing.test.service;

  2. public interface PersonService {

  3. public void save();

  4. }

服务实现类:PersonServiceImp.java

Java代码

  1. package com.luojing.test.serviceimp;

  2. import com.luojing.test.dao.PersonDao;

  3. import com.luojing.test.service.PersonService;

  4. public class PersonServiceImp implements PersonService {

  5. private PersonDao personDao;

  6. public PersonDao getPersonDao() {

  7. return personDao;

  8. }

  9. public void setPersonDao(PersonDao personDao) {

  10. this.personDao = personDao;

  11. }

  12. public void save() {

  13. personDao.add();

  14. }

  15. }

applicationContext.xml配置文件如下:

Java代码

  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <beans xmlns="http://www.springframework.org/schema/beans"

  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  4. xsi:schemaLocation="http://www.springframework.org/schema/beans

  5. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" >

  6. <bean id="personDao" class="com.luojing.test.daoimp.PersonDaoImp"/>

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

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

  9. </bean>

  10. </beans>

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

Java代码

  1. package com.luojing.test.testioc;

  2. import java.util.ArrayList;

  3. import java.util.List;

  4. public class BeanDefinition {

  5. private String id;

  6. private String classname;

  7. private List<PropertyDefinition> propertys = new ArrayList<PropertyDefinition>();

  8. public String getId() {

  9. return id;

  10. }

  11. public void setId(String id) {

  12. this.id = id;

  13. }

  14. public String getClassname() {

  15. return classname;

  16. }

  17. public void setClassname(String classname) {

  18. this.classname = classname;

  19. }

  20. public List<PropertyDefinition> getPropertys() {

  21. return propertys;

  22. }

  23. public void setPropertys(List<PropertyDefinition> propertys) {

  24. this.propertys = propertys;

  25. }

  26. public BeanDefinition(String id,String classname){

  27. this.id = id;

  28. this.classname = classname;

  29. }

  30. }

属性bean PropertyDefinition.java:

Java代码

  1. package com.luojing.test.testioc;

  2. public class PropertyDefinition {

  3. private String name;

  4. private String ref;

  5. public String getName() {

  6. return name;

  7. }

  8. public void setName(String name) {

  9. this.name = name;

  10. }

  11. public String getRef() {

  12. return ref;

  13. }

  14. public void setRef(String ref) {

  15. this.ref = ref;

  16. }

  17. public PropertyDefinition(String name,String ref){

  18. this.name = name;

  19. this.ref = ref;

  20. }

  21. }

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

Java代码

  1. package com.luojing.test.testioc;

  2. import java.beans.Introspector;

  3. import java.beans.PropertyDescriptor;

  4. import java.lang.reflect.Method;

  5. import java.net.URL;

  6. import java.util.ArrayList;

  7. import java.util.HashMap;

  8. import java.util.List;

  9. import java.util.Map;

  10. import org.dom4j.Document;

  11. import org.dom4j.Element;

  12. import org.dom4j.XPath;

  13. import org.dom4j.io.SAXReader;

  14. public class ItcastClassPathXMLApplicationContext {

  15. private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();

  16. private Map<String, Object> sigletons = new HashMap<String, Object>();

  17. public ItcastClassPathXMLApplicationContext(String filename){

  18. this.readXML(filename);

  19. this.instanceBeans();

  20. this.injectObject();

  21. }

  22. /**

  23. * 实现bean的实例化

  24. */

  25. private void instanceBeans() {

  26. for (BeanDefinition beanDefinition : beanDefines) {

  27. try {

  28. if (beanDefinition.getClassname() != null && !"".equals(beanDefinition.getClassname().trim()))

  29. sigletons.put(beanDefinition.getId(), Class.forName(

  30. beanDefinition.getClassname()).newInstance());

  31. } catch (Exception e) {

  32. // 通过反射技术把bean都创建出来

  33. e.printStackTrace();

  34. }

  35. }

  36. }

  37. /**

  38. * 为bean对象的属性注入值

  39. */

  40. private void injectObject() {

  41. for (BeanDefinition beanDefinition : beanDefines) {

  42. Object bean = sigletons.get(beanDefinition.getId());

  43. if (bean != null) {

  44. try {

  45. PropertyDescriptor[] ps = Introspector.getBeanInfo(

  46. bean.getClass()).getPropertyDescriptors();

  47. //Introspector通过这个类可以取得bean的定义信息

  48. for (PropertyDefinition propertyDefinition : beanDefinition

  49. .getPropertys()) {

  50. for (PropertyDescriptor properdesc : ps) {

  51. if (propertyDefinition.getName().equals(properdesc.getName())) {

  52. Method setter = properdesc.getWriteMethod();// 获取属性的setter方法

  53. // ,private

  54. if (setter != null) {//属性可能没有set方法,所以这里要判断一下

  55. Object value = sigletons

  56. .get(propertyDefinition.getRef());

  57. setter.setAccessible(true);//如果set方法是私有的话,要设置它允许被访问

  58. setter.invoke(bean, value);// 把引用对象注入到属性

  59. }

  60. break;

  61. }

  62. }

  63. }

  64. } catch (Exception e) {

  65. }

  66. }

  67. }

  68. }

  69. /**

  70. * 读取xml配置文件

  71. */

  72. private void readXML(String filename) {

  73. SAXReader saxReader = new SAXReader();

  74. Document document = null;

  75. try {

  76. URL xmlpath = this.getClass().getClassLoader()

  77. .getResource(filename);

  78. document = saxReader.read(xmlpath);

  79. Map<String, String> nsMap = new HashMap<String, String>();

  80. nsMap.put("ns", "http://www.springframework.org/schema/beans");// 加入命名空间

  81. XPath xsub = document.createXPath("//ns:beans/ns:bean");// 创建beans/bean查询路径

  82. xsub.setNamespaceURIs(nsMap);// 设置命名空间

  83. List<Element> beans = xsub.selectNodes(document);// 获取文档下所有bean节点

  84. for (Element element : beans) {

  85. String id = element.attributeValue("id");// 获取id属性值

  86. String clazz = element.attributeValue("class"); // 获取class属性值

  87. System.out.println(id + " = " + clazz);

  88. BeanDefinition beanDefine = new BeanDefinition(id, clazz);

  89. XPath propertysub = element.createXPath("ns:property");

  90. propertysub.setNamespaceURIs(nsMap);// 设置命名空间

  91. List<Element> propertys = propertysub.selectNodes(element);

  92. for (Element property : propertys) {

  93. String propertyName = property.attributeValue("name");

  94. String propertyref = property.attributeValue("ref");

  95. System.out.println(propertyName + " = " + propertyref);

  96. PropertyDefinition propertyDefinition = new PropertyDefinition(

  97. propertyName, propertyref);

  98. beanDefine.getPropertys().add(propertyDefinition);

  99. }

  100. beanDefines.add(beanDefine);

  101. }

  102. } catch (Exception e) {

  103. e.printStackTrace();

  104. }

  105. }

  106. /**

  107. * 获取bean实例

  108. */

  109. public Object getBean(String beanName) {

  110. return this.sigletons.get(beanName);

  111. }

  112. }

测试类SpringTest.java:

Java代码

  1. package com.luojing.test.testioc;

  2. import com.luojing.test.service.PersonService;

  3. public class SpringTest {

  4. public static void main(String[] args) {

  5. ItcastClassPathXMLApplicationContext ctx = new ItcastClassPathXMLApplicationContext("applicationContext.xml");

  6. PersonService ps = (PersonService)ctx.getBean("service");

  7. ps.save();

  8. }

  9. }

spring依赖注入原理(转载)相关推荐

  1. spring依赖注入原理详解(转载)

    spring依赖注入原理详解----转载 所谓依赖注入就是指:在运行期,由外部容器动态地将依赖对象注入到组件中.当spring容器启动后,spring容器初始化,创建并管理bean对象,以及销毁它.所 ...

  2. Java程序员进阶——Spring依赖注入原理分析

    Spring依赖注入原理分析 下面谈谈Spring是如何实现反转模式IOC或依赖注入模式DI: 平时,我们需要生成一个对象,使用new语法,如一个类为A public class A{public v ...

  3. spring依赖注入原理详解

    所谓依赖注入就是指:在运行期,由外部容器动态地将依赖对象注入到组件中.当spring容器启动后,spring容器初始化,创建并管理bean对象,以及销毁它.所以我们只需从容器直接获取Bean对象就行, ...

  4. (转)编码剖析Spring依赖注入的原理

    http://blog.csdn.net/yerenyuan_pku/article/details/52834561 Spring的依赖注入 前面我们就已经讲过所谓依赖注入就是指:在运行期,由外部容 ...

  5. Spring Setter注入原理

    本文内容如有错误.不足之处,欢迎技术爱好者们一同探讨,在本文下面讨论区留言,感谢.欢迎转载,转载请注明出处(https://blog.csdn.net/feng_xiaoshi/article/det ...

  6. java接口注入对象的意义_Java Web系列:Spring依赖注入基础

    一.Spring简介 1.Spring简化Java开发 Spring Framework是一个应用框架,框架一般是半成品,我们在框架的基础上可以不用每个项目自己实现架构.基础设施和常用功能性组件,而是 ...

  7. Spring依赖注入:注解注入总结

    更多11 spring 依赖注入 注解 java 注解注入顾名思义就是通过注解来实现注入,Spring和注入相关的常见注解有Autowired.Resource.Qualifier.Service.C ...

  8. diy实现spring依赖注入

    [README] 本文diy代码实现了 spring 依赖注入,一定程度上揭示了依赖注入原理: [1]控制反转-Inversion of Control 是一种编码思想,简而言之就是 应用程序A可以使 ...

  9. spring依赖注入_Spring依赖注入

    spring依赖注入 介绍: 在设计良好的Java应用程序中,这些类应尽可能独立. 这样的设计提高了组件的可重用性. 它还使对各个组件进行单元测试变得更加容易. 依赖注入的概念促进了Java对象之间的 ...

最新文章

  1. Flask的多app应用,多线程如何体现
  2. JQuery中text()、html()和val()的区别
  3. Lotus 下部门间用户的移动操作
  4. C语言/C++编程的起源与能力学习
  5. python列表套着列表_python 列表套列表去重
  6. oracle双机热备份方法(转)
  7. matlab能做财务报表吗,基于Matlab 的零售企业财务报表分析.pdf
  8. Incorrect string value: '\xF0\x9F\x91\x93\xF0\x9F...' for column 'xxx' at row 1
  9. Android 实现动态背景“五彩蛛网”特效,让你大开眼界!
  10. java scavenge_Java垃圾收集器之Parallel Scavenge收集器
  11. 1到100号的灯开关问题
  12. html中font-family样式,详解中文字体在CSS样式中font-family对应的英文名称
  13. java两周考核期被辞退_试用期被辞退,会影响一整年,或整个职场生涯
  14. Word文档翻译成中文的方法
  15. linux的各种自带库-lz -lrt -lm -lc都是什么库
  16. 区间再现公式的理解与应用
  17. 数据分析技术教学大纲
  18. Apache Tomcat 7 HTTP连接器
  19. 2021 华中科技大学软件学院软件体系结构考试题回忆
  20. ELF格式文件详细分析

热门文章

  1. python 使用raise语句主动抛出异常(Exception)、将异常抛出给上一级
  2. 王道计算机考研 计算机组成原理 第二章、数据的表示和运算
  3. android imageview 锯齿,android 自定义圆角ImageView以及锯齿的处理
  4. nuxt服务端php,nuxt服务端部署指南
  5. 使用mysqld --install命令时出现MSVCR120.dll文件丢失错误
  6. python语言采用编译执行方式_Python程序的执行过程 解释型语言和编译型语言
  7. html请求接口_前端工程师吐后端工程师(第八讲)——接口的开发
  8. ue4 classuobject没有成员beginplay_UE4中蓝图函数的泛型
  9. 两个各四只青蛙过河java_趣味算法——青蛙过河(JAVA)
  10. python手把手入门_新手必看:手把手教你入门 Python