- 浏览: 336682 次
- 性别:
- 来自: 上海
文章分类
最新评论
-
alafqq:
很好的一篇启蒙hashmap的文章;HASHTABLE的93行 ...
使用数组和链表实现hash表存储信息 -
小帅1127:
我擦,我还以为有什么大坑呢,这也写出来。。。
if..else if和if..if的区别 -
fncj:
转下http://www.dodoer.com
hadoop单机版搭建图文详解 -
yueshang520:
Spring注解原理的详细剖析与实现 -
fncj:
转下,谢谢http://www.whohelpme.com/b ...
Spring注解原理的详细剖析与实现
首先,做一个配置属性的基本测试。修改beans.xml,使引用外部类变成内部bean属性:
<?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="peopleDao" class="com.wxy.dao.impl.PeopleDaoBean"></bean>
<bean id="peopleService" class="com.wxy.service.impl.PeopleServiceBean">
<property name="peopleDao" ref=” peopleDao”/>
</bean>
</beans>
测试:
public class Test {
public static void main(String[] args) {
//IOC容器实例化
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
PeopleService peopleService = (PeopleService) ac.getBean("peopleService");
peopleService.save();
}
}
结果正常!能够引用得到(这不是废话么)
使用ref,ref所指向的bean可以被多个bean引用;ref依赖对象将作为一个属性被注入。
Spring是如何实现装配基本属性的呢?下面用源码模拟实现之:
1、 在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="peopleDao" class="com.wxy.dao.impl.PeopleDaoBean"></bean>-->
<bean id="peopleService" class="com.wxy.service.impl.PeopleServiceBean">
<property name="peopleDao" ref="com.wxy.dao.impl.PeopleDaoBean"/>
<property name="name" value="wxy"/>
<property name="id" value="218"/>
</bean>
</beans>
2、在属性Bean:PorpertyDefinition中定义相应的属性,用来存放xml文件中定义的属性:
package com.wxy.bean;
/**
* 存放bean的property属性
*
* @creator xiaoyu.wang
* @create-time 2011-8-10 下午04:40:07
* @revision $Id
*/
public class PropertyDefinition {
private String name; //属性名
private String ref; //属性依赖对象
private String value;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the ref
*/
public String getRef() {
return ref;
}
/**
* @param ref the ref to set
*/
public void setRef(String ref) {
this.ref = ref;
}
public PropertyDefinition(String name, String ref, String value) {
super();
this.name = name;
this.ref = ref;
this.value = value;
}
/**
* @return the value
*/
public String getValue() {
return value;
}
/**
* @param value the value to set
*/
public void setValue(String value) {
this.value = value;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "PropertyDefinition [name=" + name + ", ref=" + ref + ", value=" + value + "]";
}
}
3、 修改PeopelServiceBean ,添加相对应的属性:
public class PeopleServiceBean implements PeopleService {
private PeopleDao peopleDao;
private String name;
private Integer id;
/**
* @return the peopleDao
*/
public PeopleDao getPeopleDao() {
return peopleDao;
}
/**
* @param peopleDao the peopleDao to set
*/
public void setPeopleDao(PeopleDao peopleDao) {
this.peopleDao = peopleDao;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
public void save() {
System.out.println("--> the method is called save()! name=" + name + ",id=" + id);
peopleDao.add();
}
}
4、读取属性值,修改WxyClassPathXMLApplicationContext.java, 添加注入属性功能 :
package com.wxy.content;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
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.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import com.wxy.bean.BeanDefinition;
import com.wxy.bean.PropertyDefinition;
/**
* 自定义IoC容器
* BeanDefinition的resource定位:readXML();
* BeanDefinition的载入和解析 :readXML();
* BeanDefinition在IoC容器中的注册 instanceBeans();
* @create-time 2011-8-10 上午09:19:17
* @revision $Id
*/
public class WxyClassPathXMLApplicationContext {
//存放BeanDefinition的列表,在beans.xml中定义的bean可能不止一个
private final List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
//将类名作为索引,将创建的Bean对象存入到Map中
private final Map<String, Object> sigletons = new HashMap<String, Object>();
public WxyClassPathXMLApplicationContext(String fileName) {
//读取xml配置文件
this.readXML(fileName);
//实例化bean
this.instanceBeans();
//注入对象
this.injectObject();
}
/**
*为bean对象的属性注入值
*/
private void injectObject() {
for (BeanDefinition beanDefinition : beanDefines) {
//获取beanDefines中的对象
Object bean = sigletons.get(beanDefinition.getId());
if (bean != null) {
//如果存在,利用反射技术将值注入
try {
//获取Bean的描述属性类
PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass())
.getPropertyDescriptors();
for (PropertyDefinition propertyDefinition : beanDefinition.getProperties()) {
for (PropertyDescriptor properdesc : ps) {
//取得属性名字与propertyDefinition中的属性做比较
if (propertyDefinition.getName().equals(properdesc.getName())) {
//获得属性的setter方法
Method setter = properdesc.getWriteMethod();
if (setter != null) {
Object value = null;
if (propertyDefinition.getRef() != null
&& !propertyDefinition.getRef().isEmpty()) {//注入依赖对象
value = sigletons.get(propertyDefinition.getRef());
} else {//注入基本类型
//将字符串类型装换成用户需要的类型,需要用到jar包中的commons-beanutils.jar
value = ConvertUtils.convert(propertyDefinition.getValue(),
properdesc.getPropertyType());
}
//允许访私有方法
setter.setAccessible(true);
//把引用对象注入到属性
setter.invoke(bean, value);
}
}
}
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IntrospectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* 读取XML配置文件,获取BeanDefinition内容,存入到beanDefinition列表中
* @param fileName xml配置文件名称
*/
private void readXML(String fileName) {
SAXReader saxReader = new SAXReader();
Document document = null;
try {
//通过类加载器获取Resource资源路径,实现BeanDefinition的resource定位
URL xmlPath = this.getClass().getClassLoader().getResource(fileName);
//将xml读入到document中
document = saxReader.read(xmlPath);
Map<String, String> nsMap = new HashMap<String, String>();
//加入命名空间
nsMap.put("ns", "http://www.springframework.org/schema/beans");
//创建beans/bean查询路径,注意:路径前要注明命名空间,便于解析
XPath xsub = document.createXPath("//ns:beans/ns:bean");
//设置命名空间
xsub.setNamespaceURIs(nsMap);
//获取文档下的所有Bean节点
List<Element> beans = xsub.selectNodes(document);
for (Element element : beans) {
//获取id属性值
String id = element.attributeValue("id");
//获取class属性值
String clazz = element.attributeValue("class");
BeanDefinition beanDefinition = new BeanDefinition(id, clazz);
//创建bean/property查询路径
XPath propertysub = element.createXPath("ns:property");
//设置命名空间
propertysub.setNamespaceURIs(nsMap);
//获取bean的property列表节点
List<Element> properties = propertysub.selectNodes(element);
for (Element property : properties) {
String propertyName = property.attributeValue("name");
String propertyref = property.attributeValue("ref");
String propertyValue = property.attributeValue("value");
PropertyDefinition propertyDefinition = new PropertyDefinition(propertyName,
propertyref, propertyValue);
System.out.println(property);
//将property属性添加到beanDefinition中
beanDefinition.getProperties().add(propertyDefinition);
}
//将新创建的BeanDefinition赌侠ing放入到BeanDeifnitions中
beanDefines.add(beanDefinition);
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
/**
* 实例化bean,存入到sigletons中
*/
private void instanceBeans() {
for (BeanDefinition beanDefinition : beanDefines) {
try {
if (beanDefinition.getClassName() != null
&& !(beanDefinition.getClassName().isEmpty())) {
//利用java反射机制,生成BeanDefinition实例,并将其注册到sigletons中
sigletons.put(beanDefinition.getId(), Class.forName(
beanDefinition.getClassName()).newInstance());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 根据ID名获取实例bean
* return 返回一个Object对象,用户使用时,需要对获取的结果进行转换类型
*/
public Object getBean(String beanName) {
return this.sigletons.get(beanName);
}
}
5、 进行测试:
public class MyTest {
public static void main(String[] args) {
//MyIOC容器实例化
WxyClassPathXMLApplicationContext ac = new WxyClassPathXMLApplicationContext("beans.xml");
PeopleService peopleService = (PeopleService) ac.getBean("peopleService");
peopleService.save();
}
}
6、 测试结果:
--> the method is called save()! name=wxy,id=218
this is the method PeopleDaoBean.add()!
发表评论
-
apache日志信息详解
2011-11-06 21:19 6269一、访问日志的格式 Apache内建了记录服务器 ... -
使用CGLIB实现AOP功能与AOP概念解释 .
2011-08-19 10:30 1328第三方创建代理对象的框架cglib,目标类可以不实现接口 ... -
浏览器如何工作
2011-08-19 08:57 0http://taligarsiel.com/Projects ... -
编码实现用JDK中的Proxy实现springAOP功能
2011-08-18 15:04 742http://blog.csdn.net/iamtheevil ... -
Spring注解原理的详细剖析与实现
2011-08-14 23:09 84233本文主要分为三部分: ... -
编码剖析Spring依赖注入的原理
2011-08-10 20:01 1812一、注入依赖对象 基本类型对象注入: <b ... -
Spring的三种实例化Bean的方法
2011-08-10 14:03 1Spring的三种实例化Bean的方法 1、 使用 ... -
Spring管理bean的原理自定义实现
2011-08-10 10:44 61851、Spring通过BeanDefinition管理基于S ... -
spring环境搭建与测试
2011-08-10 08:40 3406Chapter1、搭建与测试spring的环境 1、 ... -
java回调机制实现
2011-08-08 09:06 2033Java的接口支持提供了一种获得回调的等价功能的 ... -
log4j的使用与详细分析
2011-08-05 13:32 2624一、什么是log4j? http://logging.a ... -
log4j使用详解
2011-08-04 23:05 2http://logging.apache.org/log4j ... -
spring入门及Demo
2011-07-29 16:01 0一、Spring是什么? Spring是一个开源框架,它 ... -
ibatis入门及环境搭建
2011-07-23 12:27 1413使用ibatis的理由: 1. 知道怎样操作10种以上 ... -
山寨Hibernate
2011-04-09 23:32 0---------------------------- ... -
java解析XML的四种方法的学习与比较
2011-03-30 20:55 7228四种XML解析方法: ... -
自定义日志模块实现
2011-03-30 09:58 1101package wxy.XXXX.Utils; impo ... -
synchronized(this)
2011-03-29 09:17 69361、当两个并发线程访问同一个对象object中的这个synch ... -
详细解析Java中抽象类和接口的区别(转)
2011-03-24 23:48 922在Java语言中, abstract cl ... -
首次配置hibernate碰到的各种问题
2011-03-15 21:18 14891、java.lang.NoClassDefFoundErro ...
相关推荐
编码剖析Spring装配基本属性的原理
Spring Boot实战与原理分析视频课程包含14-18,本视频教程为网络整理,如有侵权,请联系删除。谢谢 Spring Boot实战与原理分析视频课程 课程目录: 1 Spring Boot概述与课程概要介绍20:33 2 Spring4 快速入门59:56...
本项目为Java项目,使用Spring实现自动装配,根据类型方式实现自动装配。适合初学者了解Spring不同装配方式。
如果你以一种淡定的心态翻开这本书,无论你是Java程序员、Spring开发者,还是平台开发人员、系统架构师,抑或是对开源软件源代码着迷的代码狂人,都能从《Spring技术内幕:深入解析Spring架构与设计原理》中受益。...
《Spring技术内幕:深入解析Spring架构与设计原理(第2版)》从源代码的角度对Spring的内核和各个主要功能模块的架构、设计和实现原理进行了深入剖析。你不仅能从本书中参透Spring框架的出色架构和设计思想,还能从...
spring ioc指的是控制反转,IOC容器负责实例化、定位、配置应用程序中的对象及建立这些对象间的依赖。交由Spring容器统一进行管理,从而实现松耦合
本书从源代码的角度对Spring的内核和各个主要功能模块的架构、设计和实现原理进行了深入剖析。你不仅能从本书中参透Spring框架的优秀架构和设计思想,还能从Spring优雅的实现源码中一窥Java语言的精髓。本书在开篇...
这是对Spring中注解是怎么实现的一个大概基本原理,条件是采取的理想状态,所以代码中还有缺陷的话请谅解,如果有需要的朋友可以放心下载,里面有详细的解释和流程。相信你能看懂
深度剖析Spring Boot自动装配机制实现原理(csdn)————程序
1、spring boot 新手入门,可以快速掌握spring boot的基本使用
Spring技术内幕:深入解析Spring架构与设计原理.pdf
Spring Boot实战与原理分析视频课程 主要讲解了spring boot的原理分析--服务注册发现,注解,日志配置等等
Spring Boot实战与原理分析视频课程 课程目录: 1 Spring Boot概述与课程概要介绍20:33 2 Spring4 快速入门59:56 3 Spring4 扩展分析(一)35:49 4 Spring4 扩展分析(二)21:11 5 Spring Boot 快速入门24:01 ...
NULL 博文链接:https://zhang-yingjie-qq-com.iteye.com/blog/319927
主要为大家详细介绍了Java注解机制之Spring自动装配实现原理,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
在Spring中可以装配4种集合类型属性:List、set、Map和Properties。与这四种集合对应的标签是、、、。CollectionBean是一个包含上述4种集合类型的JavaBean,代码如下:
Spring源代码解析(一):IOC容器 Spring源代码解析(二):IoC容器在Web容器中的启动 Spring源代码解析(三):Spring JDBC Spring源代码解析(四):Spring MVC ...Spring源代码解析(十):Spring Acegi框架授权的实现
Spring源代码分析(三):Spring JDBC Spring源代码解析(四):Spring MVC Spring源代码解析(五):Spring AOP获取Proxy Spring源代码解析(六):Spring声明式事务处理 Spring源代码解析(七):Spring AOP中对拦截器...
基于java实现的类似spring自动装配的代码。