您的位置:首页 > 编程语言 > Java开发

研究spring原理的心得

2015-07-26 17:40 453 查看
下面是我研究spring原理的心得。通过配置文件加实例化对象,并注入属性值 。

spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="person" class="com.bing.model.Person">
<property name="name" value="yuanbin"/>
<property name="email" value="yuan1191@126.com"/>
<property name="birthday" ref="birthday"/>
</bean>
<bean id="birthday" class="com.bing.model.Birthday">
<property name="xingzuo" value="天蝎座"></property>
<property name="months">
<map>
<entry key="1">
<value>one</value>
</entry>
<entry key="2">
<value>two</value>
</entry>
</map>
</property>
</bean>
</beans>

package testProject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.bing.model.Bean;

/**
* 解析spring文件
* @author yuan
*
*/
public class ParseResouce {

/**
* 解析spring.xml
* @return
* @throws Exception
*/
public Map<String,Object> parseResource(String path) throws Exception{
//存放配置文件中所有的bean信息
Map<String,Object> map = new HashMap<String,Object>();
SAXReader read = new SAXReader();
Document document = read.read(path);
Element root = document.getRootElement();
Iterator iterator = root.elements().iterator();
while(iterator.hasNext()){
Element bean = (Element)iterator.next();
//单个bean的信息
Bean springBean  = new Bean();
//类的属性信息
Map<String,Object> properties = new HashMap<String,Object>();
//bean 的ID
String id = bean.attributeValue("id");
//bean 的class
String className = bean.attributeValue("class");
//属性信息
if(bean.elements().size()>0){
Iterator proIterator =  bean.elements().iterator();
while(proIterator.hasNext()){
Element property = (Element)proIterator.next();
String propertyName = property.attributeValue("name");
String propertyValue = property.attributeValue("value");
//map类型
if(property.element("map") != null){
Element mapElement  = property.element("map");
Iterator mapIterator =  mapElement.elements().iterator();
Map<String,Object> mapProerties = new HashMap<String,Object>();
while(mapIterator.hasNext()){
Element entry = (Element)mapIterator.next();
String mapKey = entry.attributeValue("key");
String mapValue = entry.element("value").getText();
mapProerties.put(mapKey, mapValue);
}

properties.put(propertyName, mapProerties);

}else{
//判断是value属性还是ref属性
if(propertyValue==null){
String propertyRef = property.attributeValue("ref");
if(propertyRef!=null){
properties.put(propertyName, new String[]{propertyRef});
}
}else{
properties.put(propertyName, propertyValue);
}
}

}
}
springBean.setId(id);
springBean.setType(className);
springBean.setProperties(properties);
map.put(id, springBean);
}
return map;
}

}

package testProject;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import com.bing.model.Bean;

/*
*
*模拟解析spring配置文件
*
*/
public class ParseSpringXml {

/**
* 解析springxml文件,注入并返回对象
* @param path
* @return
* @throws Exception
*/
public Map<String,Object> parseSpringXml(String path) throws Exception{
//存放注入属性后的所有bean信息
Map<String,Object> map = new HashMap<String,Object>();
//spring配置文件的信息
Map<String,Object> beanMap= new ParseResouce().parseResource(path);
for(Map.Entry<String, Object> entry : beanMap.entrySet()){
//已经实例化了并已设置过属性值的跳过
if(map.get(entry.getKey())!=null){
continue;
}
//得到实例后的对象
Object object = reflectBean(beanMap, map, entry.getKey());
//存放于集合中
map.put(entry.getKey(), object);
}
return map;
}

/**
* 设置属性值
* @param object
* @param methodName
* @param Value
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
private void setProperty(Object object, String methodName, Object value) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method[] methods = object.getClass().getMethods();
//得到方法
Method method = getSetMethod(methods,methodName);
//设置访问权限
method.setAccessible(true);
//给对象赋值
method.invoke(object, value);

}

/**
*
* 根据方法名,找到该方法的set方法
*
* @param methods
* @param methodName
* @return
*/
private Method getSetMethod(Method[] methods, String methodName) {
for(Method method:methods){
String tempMethodName = "set"+methodName.substring(0, 1).toUpperCase()+methodName.substring(1);
String tempIsMethodName = "is"+methodName.substring(0, 1).toUpperCase()+methodName.substring(1);
if(method.getName().equals(tempMethodName)){
return method;
}else if(method.getName().equals(tempIsMethodName)){
return method;
}

}
return null;
}

/**
* 根据class得到其实例
* @param type
* @return
*/
private  Object  getInstance(String type){
Object obj = null;
Class<?> classs = null;
try {
classs = Class.forName(type);
obj = classs.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}

return obj;

}

/**
* 通过反射,将beanId实例化并设置相应的属性值
*
* @param beanMap
* @param map
* @param beanId
* @return
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*/
public Object reflectBean(Map<String,Object> beanMap,Map<String,Object> map ,String beanId) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
//已经实例化了并已设置过属性值
if(map.get(beanId)!=null){
return map.get(beanId);
}
Bean bean =  (Bean)beanMap.get(beanId);
//实例化对象
Object object = getInstance(bean.getType());
//设置属性值
for(String key:bean.getProperties().keySet()){
//设置属性值
//ref的处理
if(bean.getProperties().get(key) instanceof String[]){

if(map.get(key)==null){
//ref对象未设置过属性值
String[] refValue = (String[]) bean.getProperties().get(key);
Object obj = reflectBean(beanMap, map, refValue[0]);
setProperty(object,key,obj);
}else{
//ref对象已经已经实例化了并已设置过属性值
setProperty(object,key,map.get(key));
}
}else{
//value的处理
setProperty(object,key,bean.getProperties().get(key));
}
}
return object;
}

}

Bean类:
package com.bing.model;

import java.util.HashMap;
import java.util.Map;

public class Bean {
private String id;
private String type;
private Map<String,Object> properties = new HashMap();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Map<String, Object> getProperties() {
return properties;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}
@Override
public String toString() {
return "Bean [id=" + id + ", type=" + type + ", properties="
+ properties + "]";
}

}

public class Person {
private String name;
private String passowrd;
private int Age;
private String email;
private String uNit;
private Birthday birthday;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassowrd() {
return passowrd;
}
public void setPassowrd(String passowrd) {
this.passowrd = passowrd;
}

public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}

public Birthday getBirthday() {
return birthday;
}
public void setBirthday(Birthday birthday) {
this.birthday = birthday;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
public String getuNit() {
return uNit;
}
public void setuNit(String uNit) {
this.uNit = uNit;
}
@Override
public String toString() {
return "Person [name=" + name + ", passowrd=" + passowrd + ", Age="
+ Age + ", email=" + email + ", uNit=" + uNit + ", birthday="
+ birthday + "]";
}

}

package com.bing.model;

import java.util.Map;

public class Birthday {
private String date;    //日期
private String desc;    //说明
private String xingzuo;   //星座
private Map<String,Object> months;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getXingzuo() {
return xingzuo;
}
public void setXingzuo(String xingzuo) {
this.xingzuo = xingzuo;
}
public Map<String, Object> getMonths() {
return months;
}
public void setMonths(Map<String, Object> months) {
this.months = months;
}

@Override
public String toString() {
return "Birthday [date=" + date + ", desc=" + desc + ", xingzuo="
+ xingzuo + ", months=" + months + "]";
}

}

package testProject;

import java.util.Map;

客户端:

public class Application {
public static void main(String[] args) {
ParseSpringXml parseSpringXml = new ParseSpringXml();
String path="src/main/resources/application.xml";
try {
Map<String,Object> map = parseSpringXml.parseSpringXml(path);       System.out.println(map.get("person"));

} catch (Exception e) {
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: