Spring解析实践
这几天重新把传智播客的黎活明的Spring2.5的教程学习了一遍,跟着上面的解析Spring的过程跟着制作了一个简单的Spring IOC和Spring AOP,先在贴上来给大家参考一下。
1:管理Bean和依赖注入 配制文件bean.xml格式如下模板所示:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.ganggang.com/beans"> <bean id="personDao" class="com.ganggang.dao.impl.PersonDaoImpl"> </bean>
<bean id="personService" class="com.ganggang.service.impl.PersonServiceImpl">
<property name="no" value="0704685003"/>
</bean>
</beans>
用一个名为XmlApplication的类从bean.xml中读取相应的bean的配制信息并根据需要返回想要实例化的bean的实例对象。
public class XmlApplication {
private List<BeanDefinition> beans=new ArrayList<BeanDefinition>();
private Map<String,Object> objs=new HashMap<String, Object>();
public XmlApplication(String file){
this.readXml(file);
this.instance();
this.annotationInject();
this.injectObject();
................ }
}
XmlApplication对象实例化时,先用readXml函数读取bean.xml中的bean配置信息,将每个bean实例化成BeanDefinition对象并存储在名为beans的链表中,BeanDefinition定义如下:
public class BeanDefinition {
private String id;
private String className;
private List<PropertyDefinition> propertys=new ArrayList<PropertyDefinition>();
public BeanDefinition(String id, String className) {
this.id = id;
this.className = className;
}
...........getter和setter方法
}
BeanDefinition中的propertys用来表示每个bean中的属性,每个属性即是一个PropertyDefinition型对象,PropertyDefinition定义如下:
public class PropertyDefinition {
private String name;
private String ref;
private String value;
public PropertyDefinition(String name, String ref,String value) {
this.name = name;
this.ref = ref;
this.value=value;
}
.................getter和setter方法
}
readXml函数的代码如下:
private void readXml(String file) {
SAXReader saxReader = new SAXReader();
Document document=null;
try{
URL xmlpath = this.getClass().getClassLoader().getResource(file);
document = saxReader.read(xmlpath);
Map<String,String> nsMap = new HashMap<String,String>();
nsMap.put("ns","http://www.ganggang.com/beans");//加入命名空间
XPath xsub = document.createXPath("//ns:beans/ns:bean");//创建beans/bean查询路径
xsub.setNamespaceURIs(nsMap);//设置命名空间
List<Element> beanss = xsub.selectNodes(document);//获取文档下所有bean节点
for(Element element: beanss){
String id = element.attributeValue("id");//获取id属性值
System.out.println(id);
String clazz = element.attributeValue("class"); //获取class属性值
BeanDefinition beanDefine = new BeanDefinition(id, clazz);
//开始处理property
XPath propertysub=element.createXPath("ns:property");
propertysub.setNamespaceURIs(nsMap);
List<Element> props=propertysub.selectNodes(element);
for(Element e:props){
String name=e.attributeValue("name");
String ref=e.attributeValue("ref");
String val=e.attributeValue("value");
PropertyDefinition propertyDefinition=new PropertyDefinition(name,ref,val);
beanDefine.getPropertys().add(propertyDefinition);
System.out.println("name:"+name+";value:"+val);
}
//除了你property完毕
beans.add(beanDefine);
}
}catch(Exception e){
e.printStackTrace();
}
}
然后,XmlApplication再调用instance方法实例化beans中的bean,并将每个bean对象存储在map型的objs中,objs中的key即为每个bean的id。
private void instance() {
for(BeanDefinition bean:beans){
try {
objs.put(bean.getId(), Class.forName(bean.getClassName()).newInstance());
System.out.println(bean.getId());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
最后进行依赖注入,本程序同时支持注解注入和xml配制文件注入,根据实际需要选择注入方式。其中annotationInject函数执行注解注入,injectObject函数执行配制文件注入。代码如下:
private void annotationInject() {
for(String beanName:objs.keySet()){
Object bean=objs.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(Resource.class)){
Resource resource=setter.getAnnotation(Resource.class);
Object value=null;
if(resource.name()!=null&&!"".equals(resource.name())){
value=objs.get(resource.name());
}else{
value=objs.get(properdesc.getName());
if(value==null){
for(String key:objs.keySet()){
if(properdesc.getPropertyType().isAssignableFrom(objs.get(key).getClass())){
value=objs.get(key);
break;
}
}
}
}
setter.setAccessible(true);
setter.invoke(bean, value);
}
}
Field[] fields= bean.getClass().getDeclaredFields();
for(Field field:fields){
if(field.isAnnotationPresent(Resource.class)){
Resource resource=field.getAnnotation(Resource.class);
Object value=null;
if(resource.name()!=null&&!"".equals(resource.name())){
value=objs.get(resource.name());
}else{
value=objs.get(field.getName());
if(value==null){
for(String key:objs.keySet()){
if(field.getType().isAssignableFrom(objs.get(key).getClass())){
value=objs.get(key);
break;
}
}
}
}
field.setAccessible(true);
field.set(bean, value);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private void injectObject() {
for(BeanDefinition beanDefinition:beans){
Object bean=objs.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();
if(setter!=null){
Object value=null;
if(propertyDefinition.getRef()!=null&&!"".equals(propertyDefinition.getRef().trim())){
value=objs.get(propertyDefinition.getRef());
}else{
value=ConvertUtils.convert(propertyDefinition.getValue(), properdesc.getPropertyType());
}
setter.setAccessible(true);
setter.invoke(bean, value);
}
break;
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
注入函数遍历beans中的每一个bean,如果其中有相应的property需要注入,就从objs中取得相应的实例对象注入。
XmlApplication含有一个获取相应bean的实力的函数,名为getObj,代码如下:
public Object getObj(String id){
return objs.get(id);
}
您只需在bean.xml中配制相应的bean就可以实例化一个XmlApplication对象调用getObj函数控制反转出相应的Bean的实例。
2.动态代理实现AOP
有两种,JDKProxy实现动态代理和CGLib实现。
JDKProxy实现的代码如下:
public class JDKProxyFactory implements InvocationHandler{
private Object targetObject;
public Object createProxyInstance(Object targetObject){
this.targetObject=targetObject;
return Proxy.newProxyInstance(this.targetObject.getClass().getClassLoader(),
this.targetObject.getClass().getInterfaces(),
this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
PersonServiceBean bean=(PersonServiceBean)this.targetObject;
Object result=null;
if(bean.getUser()!=null){
result=method.invoke(targetObject, args);
}
return result;
}
}
CGLib实现的代码如下:
public class CGligProxyFactory implements MethodInterceptor{
private Object targetObject;
public Object createProxyInstance(Object targetObject){
this.targetObject=targetObject;
Enhancer enhancer=new Enhancer();
enhancer.setSuperclass(this.targetObject.getClass());
enhancer.setCallback(this);
return enhancer.create();
}
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
PersonServiceBean bean=(PersonServiceBean)this.targetObject;
Object result=null;
if(bean.getUser()!=null){
result=methodProxy.invoke(targetObject, args);
}
return null;
}
Spring解析实践的更多相关文章
- Spring MVC 实践 - Component
Spring MVC 实践 标签 : Java与Web Converter Spring MVC的数据绑定并非没有任何限制, 有案例表明: Spring在如何正确绑定数据方面是杂乱无章的. 比如: S ...
- Spring MVC 实践 - Base
Spring MVC 实践 标签 : Java与Web Spring Web MVC Spring-Web-MVC是一种基于请求驱动的轻量级Web-MVC设计模式框架, Spring MVC使用MVC ...
- Spring+MyBatis实践—MyBatis数据库访问
关于spring整合mybatis的工程配置,已经在Spring+MyBatis实践—工程配置中全部详细列出.在此,记录一下几种通过MyBatis访问数据库的方式. 通过sqlSessionTempl ...
- Spring Boot实践——Spring AOP实现之动态代理
Spring AOP 介绍 AOP的介绍可以查看 Spring Boot实践——AOP实现 与AspectJ的静态代理不同,Spring AOP使用的动态代理,所谓的动态代理就是说AOP框架不会去修改 ...
- Spring Boot实践——AOP实现
借鉴:http://www.cnblogs.com/xrq730/p/4919025.html https://blog.csdn.net/zhaokejin521/article/detai ...
- 曹工说Spring Boot源码(7)-- Spring解析xml文件,到底从中得到了什么(上)
写在前面的话 相关背景及资源: 曹工说Spring Boot源码(1)-- Bean Definition到底是什么,附spring思维导图分享 曹工说Spring Boot源码(2)-- Bean ...
- 曹工说Spring Boot源码(8)-- Spring解析xml文件,到底从中得到了什么(util命名空间)
写在前面的话 相关背景及资源: 曹工说Spring Boot源码(1)-- Bean Definition到底是什么,附spring思维导图分享 曹工说Spring Boot源码(2)-- Bean ...
- 曹工说Spring Boot源码(9)-- Spring解析xml文件,到底从中得到了什么(context命名空间上)
写在前面的话 相关背景及资源: 曹工说Spring Boot源码(1)-- Bean Definition到底是什么,附spring思维导图分享 曹工说Spring Boot源码(2)-- Bean ...
- # 曹工说Spring Boot源码(10)-- Spring解析xml文件,到底从中得到了什么(context:annotation-config 解析)
写在前面的话 相关背景及资源: 曹工说Spring Boot源码(1)-- Bean Definition到底是什么,附spring思维导图分享 曹工说Spring Boot源码(2)-- Bean ...
随机推荐
- jqMobile中pageinit,pagecreate,pageshow等函数的执行顺序
常见的共有5个page函数,刚开始有点迷糊的是到底谁先谁后执行. 实验告诉我们结果: var temp = ''; $('body').live('pagechange', function () { ...
- Ueditor 上传图片 如何设置只显示 本地上传
我这个是自问自答,其实很简单.只要按照以下方式修改就可以了. 找到image.html 将以下代码 <div id="tabHeads" class="tabhea ...
- mysql常用方法学习
环境 create table phople ( id int(11) not null primary key auto_increment, name char(20) not null, sex ...
- 【BZOJ 3529】【SDOI 2014】数表
看Yveh的题解,这道题卡了好长时间,一直不明白为什么要······算了当时太naive我现在都不好意思说了 #include<cstdio> #include<cstring> ...
- JavaScript写一个连连看的游戏
天天看到别人玩连连看, 表示没有认真玩过, 不就把两个一样的图片连接在一起么, 我自己写一个都可以呢. 使用Javascript写了一个, 托管到github, 在线DEMO地址查看:打开 最终的效果 ...
- Mysql-通过case..when实现oracle decode()函数进行多值多结果判断
oracle的decode函数使用:http://www.cnblogs.com/hwaggLee/p/5335967.html case ..when 函数使用:http://www.cnblogs ...
- css-@keyframes动画
详细w3c这里 http://www.cnblogs.com/happyPawpaw/archive/2012/09/12/2681348.html Internet Explorer 10.Fire ...
- android studio-创建第一个项目
打开android studio 开始界面和Xcode有点类似,点击New project新建一个工程,新建过程和在Eclipse上差不多,这里就不赘述了. 下面开始新建项目 填写项目名称,和存放地址 ...
- json2form实例
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> ...
- 关于Yii2中CSS,JS文件的引入心得
js和css的引入 use yii\helpers\Html; 1.全局引入,所有的view生效 /assets/AppAsset.php public $css = [ 'css/site.css' ...