spring依赖注入原理(转载)
关于spring依赖注入原理的文章在网络上已经有很多,我要写的这篇文章原文出自http://taeky.iteye.com/blog/563450,只所以再一次写下来只是为了一为自己收藏,方便以后的复习;二是自己在用这个例子实践的时候遇到一些问题,自己记一下。另外这篇文章中用dom4j来解析spring的配置文件,我觉得也是个值得学习的地方。好了,不多说了,还是把代码再贴一下:
接口:PersonDao.java
Java代码
package com.luojing.test.dao;
public interface PersonDao {
public void add();
}
实现类:PersonDaoImp.java
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
Java代码
package com.luojing.test.service;
public interface PersonService {
public void save();
}
服务实现类:PersonServiceImp.java
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配置文件如下:
Java代码
<?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:
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:
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:
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:
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();
}
}
spring依赖注入原理(转载)相关推荐
- spring依赖注入原理详解(转载)
spring依赖注入原理详解----转载 所谓依赖注入就是指:在运行期,由外部容器动态地将依赖对象注入到组件中.当spring容器启动后,spring容器初始化,创建并管理bean对象,以及销毁它.所 ...
- Java程序员进阶——Spring依赖注入原理分析
Spring依赖注入原理分析 下面谈谈Spring是如何实现反转模式IOC或依赖注入模式DI: 平时,我们需要生成一个对象,使用new语法,如一个类为A public class A{public v ...
- spring依赖注入原理详解
所谓依赖注入就是指:在运行期,由外部容器动态地将依赖对象注入到组件中.当spring容器启动后,spring容器初始化,创建并管理bean对象,以及销毁它.所以我们只需从容器直接获取Bean对象就行, ...
- (转)编码剖析Spring依赖注入的原理
http://blog.csdn.net/yerenyuan_pku/article/details/52834561 Spring的依赖注入 前面我们就已经讲过所谓依赖注入就是指:在运行期,由外部容 ...
- Spring Setter注入原理
本文内容如有错误.不足之处,欢迎技术爱好者们一同探讨,在本文下面讨论区留言,感谢.欢迎转载,转载请注明出处(https://blog.csdn.net/feng_xiaoshi/article/det ...
- java接口注入对象的意义_Java Web系列:Spring依赖注入基础
一.Spring简介 1.Spring简化Java开发 Spring Framework是一个应用框架,框架一般是半成品,我们在框架的基础上可以不用每个项目自己实现架构.基础设施和常用功能性组件,而是 ...
- Spring依赖注入:注解注入总结
更多11 spring 依赖注入 注解 java 注解注入顾名思义就是通过注解来实现注入,Spring和注入相关的常见注解有Autowired.Resource.Qualifier.Service.C ...
- diy实现spring依赖注入
[README] 本文diy代码实现了 spring 依赖注入,一定程度上揭示了依赖注入原理: [1]控制反转-Inversion of Control 是一种编码思想,简而言之就是 应用程序A可以使 ...
- spring依赖注入_Spring依赖注入
spring依赖注入 介绍: 在设计良好的Java应用程序中,这些类应尽可能独立. 这样的设计提高了组件的可重用性. 它还使对各个组件进行单元测试变得更加容易. 依赖注入的概念促进了Java对象之间的 ...
最新文章
- Flask的多app应用,多线程如何体现
- JQuery中text()、html()和val()的区别
- Lotus 下部门间用户的移动操作
- C语言/C++编程的起源与能力学习
- python列表套着列表_python 列表套列表去重
- oracle双机热备份方法(转)
- matlab能做财务报表吗,基于Matlab 的零售企业财务报表分析.pdf
- Incorrect string value: '\xF0\x9F\x91\x93\xF0\x9F...' for column 'xxx' at row 1
- Android 实现动态背景“五彩蛛网”特效,让你大开眼界!
- java scavenge_Java垃圾收集器之Parallel Scavenge收集器
- 1到100号的灯开关问题
- html中font-family样式,详解中文字体在CSS样式中font-family对应的英文名称
- java两周考核期被辞退_试用期被辞退,会影响一整年,或整个职场生涯
- Word文档翻译成中文的方法
- linux的各种自带库-lz -lrt -lm -lc都是什么库
- 区间再现公式的理解与应用
- 数据分析技术教学大纲
- Apache Tomcat 7 HTTP连接器
- 2021 华中科技大学软件学院软件体系结构考试题回忆
- ELF格式文件详细分析
热门文章
- python 使用raise语句主动抛出异常(Exception)、将异常抛出给上一级
- 王道计算机考研 计算机组成原理 第二章、数据的表示和运算
- android imageview 锯齿,android 自定义圆角ImageView以及锯齿的处理
- nuxt服务端php,nuxt服务端部署指南
- 使用mysqld --install命令时出现MSVCR120.dll文件丢失错误
- python语言采用编译执行方式_Python程序的执行过程 解释型语言和编译型语言
- html请求接口_前端工程师吐后端工程师(第八讲)——接口的开发
- ue4 classuobject没有成员beginplay_UE4中蓝图函数的泛型
- 两个各四只青蛙过河java_趣味算法——青蛙过河(JAVA)
- python手把手入门_新手必看:手把手教你入门 Python