框架部分
public abstract class ApplicationContext {
public abstract Object getBean(String id);
}
public class BeanDefinetion {
private String id;
private String type;
private List<PropertyDefinition> propertyDefinitions=new ArrayList<PropertyDefinition>();
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 List<PropertyDefinition> getPropertyDefinitions() {
return propertyDefinitions;
}
public void setPropertyDefinitions(List<PropertyDefinition> propertyDefinitions) {
this.propertyDefinitions = propertyDefinitions;
}
public BeanDefinetion(String id, String type) {
this.id = id;
this.type = type;
}
}
public class PropertyDefinition {
private String name;
private String ref;
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
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,String value) {
this.name = name;
this.ref = ref;
this.value=value;
}
}
属性或字段注入注解
@Target({ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface YmResource {
public String name() default "";
}
对象注解
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface YmService {
String value() default "";
}
容器实现
package spring;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Administrator
*/
public class ClassPathXmlApplicationContext extends ApplicationContext {
private Map<String, Object> singletons = new HashMap<String, Object>();
private List<BeanDefinetion> beanDefinetions = new LinkedList<BeanDefinetion>();
private List<String> beansFile = new LinkedList<String>();
private InputStream input;
private String basepcakage;
public ClassPathXmlApplicationContext(String file) {
try {
input = getClass().getResourceAsStream(file);
parseXML();//xml解析
beanInstance();//基于xml的对象实例
beanAnnotationInstance();//基于注解的对象实例
injectObject();//基于xml的对象注入
injectAnnotationObject();//基于注解的对象注入
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void beanAnnotationInstance() throws Exception {
System.out.println(beanDefinetions);
for (BeanDefinetion beanDefinetion : beanDefinetions) {
Class z = Class.forName(beanDefinetion.getType());
singletons.put(beanDefinetion.getId(), z.newInstance());
}
System.out.println(singletons);
}
public void list(File file) throws Exception {
String id = null;
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
list(f);
}
} else {
if (file.getName().endsWith(".class")) {
// System.out.println(file.getName().replace(".class", ""));
String type = getType(file);
Class z = Class.forName(type);
if (z.isAnnotationPresent(YmService.class)) {
Annotation[] annotations = z.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation.annotationType() == YmService.class) {
id = ((YmService) annotation).value();
}
}
BeanDefinetion beanDefinetion = new BeanDefinetion(id, type);
beanDefinetions.add(beanDefinetion);
}
}
}
}
private String getType(File file) {
String path = file.getPath();
path = path.substring(path.indexOf("classes")).replace("classes" + File.separator, "");
return path.replace(File.separator, ".").replace(".class", "");
}
private void injectAnnotationObject() throws Exception {
for (BeanDefinetion beanDefinetion : beanDefinetions) {
PropertyDescriptor[] propertyDescriptors = java.beans.Introspector.getBeanInfo(Class.forName(beanDefinetion.getType())).getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
Method setter = propertyDescriptor.getWriteMethod();
if (setter != null && setter.isAnnotationPresent(YmResource.class)) {
YmResource ymResource = setter.getAnnotation(YmResource.class);
String ref = ymResource.name();
setter.setAccessible(true);
setter.invoke(singletons.get(beanDefinetion.getId()), singletons.get(ref));
}
}
Field[] fields = Class.forName(beanDefinetion.getType()).getDeclaredFields();
for (Field field : fields) {
if (field != null && field.isAnnotationPresent(YmResource.class)) {
YmResource ymResource = field.getAnnotation(YmResource.class);
String ref = ymResource.name();
field.setAccessible(true);
field.set(singletons.get(beanDefinetion.getId()), singletons.get(ref));
}
}
}
}
private void injectObject() throws Exception {
for (BeanDefinetion beanDefinetion : beanDefinetions) {
for (PropertyDefinition propertyDefinition : beanDefinetion.getPropertyDefinitions()) {
PropertyDescriptor[] propertyDescriptors = java.beans.Introspector.getBeanInfo(Class.forName(beanDefinetion.getType())).getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if (propertyDescriptor.getName().equals(propertyDefinition.getName())) {
Method setter = propertyDescriptor.getWriteMethod();
setter.setAccessible(true);
if (propertyDefinition.getValue() == null) {
setter.invoke(singletons.get(beanDefinetion.getId()), singletons.get(propertyDefinition.getName()));
} else {
setter.invoke(singletons.get(beanDefinetion.getId()), propertyDefinition.getValue());
}
}
}
}
}
}
private void parseXML() throws Exception {
SAXReader reader = new SAXReader();
Document doc = reader.read(input);
Map<String, String> ns = new HashMap<String, String>();
ns.put("ns", "http://www.springframework.org/schema/beans");
XPath xpath = doc.createXPath("//ns:beans/ns:bean");
xpath.setNamespaceURIs(ns);
List<Element> elements = xpath.selectNodes(doc);
for (Element element : elements) {
String id = element.attributeValue("id");
String type = element.attributeValue("class");
BeanDefinetion beanDefinetion = new BeanDefinetion(id, type);
beanDefinetions.add(beanDefinetion);
List<Element> propertys = element.selectNodes("property");
for (Element property : propertys) {
String name = property.attributeValue("name");
String ref = property.attributeValue("ref");
String value = property.attributeValue("value");
PropertyDefinition propertyDefinition = new PropertyDefinition(name, ref, value);
beanDefinetion.getPropertyDefinitions().add(propertyDefinition);
}
}
ns = new HashMap<String, String>();
ns.put("context", "http://www.springframework.org/schema/context");
xpath = doc.createXPath("//context:component-scan");
xpath.setNamespaceURIs(ns);
elements = xpath.selectNodes(doc);
System.out.println(elements);
Element element = elements.get(0);
basepcakage = element.attributeValue("base-package");
System.out.println(basepcakage);
try {
Enumeration enumer = ClassLoader.getSystemResources(basepcakage);
while (enumer.hasMoreElements()) {
URL path = (URL) enumer.nextElement();
list(new File(path.getFile()));
}
} catch (IOException ex) {
Logger.getLogger(ClassPathXmlApplicationContext.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void beanInstance() throws Exception {
for (BeanDefinetion beanDefinetion : beanDefinetions) {
Object o = Class.forName(beanDefinetion.getType()).newInstance();
singletons.put(beanDefinetion.getId(), o);
}
}
@Override
public Object getBean(String id) {
return singletons.get(id);
}
}
测试的部分
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context">
<context:component-scan base-package="ym"/>
<bean id="test" class="ym.Test"/>
</beans>
public interface ProductDao {
public void insert();
}
@YmService("productDao")
public class ProductDaoBean implements ProductDao{
public void insert() {
System.out.println("svae............");
}
}
public interface ProductService {
void newProduct();
}
@YmService("productService")
public class ProductServiceBean implements ProductService{
public void newProduct() {
productDao.insert();
System.out.print(name);
}
@YmResource(name="productDao") private ProductDao productDao;
public ProductDao getProductDao() {
return productDao;
}
// @YmResource(name="productDao")
public void setProductDao(ProductDao productDao) {
this.productDao = productDao;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Test {
public static void main(String[] args) {
//ProductService productService=new ProductServiceBean();
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
ProductService productService=(ProductService)ctx.getBean("productService");
productService.newProduct();
}
}
public abstract class ApplicationContext {
public abstract Object getBean(String id);
}
public class BeanDefinetion {
private String id;
private String type;
private List<PropertyDefinition> propertyDefinitions=new ArrayList<PropertyDefinition>();
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 List<PropertyDefinition> getPropertyDefinitions() {
return propertyDefinitions;
}
public void setPropertyDefinitions(List<PropertyDefinition> propertyDefinitions) {
this.propertyDefinitions = propertyDefinitions;
}
public BeanDefinetion(String id, String type) {
this.id = id;
this.type = type;
}
}
public class PropertyDefinition {
private String name;
private String ref;
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
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,String value) {
this.name = name;
this.ref = ref;
this.value=value;
}
}
属性或字段注入注解
@Target({ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface YmResource {
public String name() default "";
}
对象注解
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface YmService {
String value() default "";
}
容器实现
package spring;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Administrator
*/
public class ClassPathXmlApplicationContext extends ApplicationContext {
private Map<String, Object> singletons = new HashMap<String, Object>();
private List<BeanDefinetion> beanDefinetions = new LinkedList<BeanDefinetion>();
private List<String> beansFile = new LinkedList<String>();
private InputStream input;
private String basepcakage;
public ClassPathXmlApplicationContext(String file) {
try {
input = getClass().getResourceAsStream(file);
parseXML();//xml解析
beanInstance();//基于xml的对象实例
beanAnnotationInstance();//基于注解的对象实例
injectObject();//基于xml的对象注入
injectAnnotationObject();//基于注解的对象注入
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void beanAnnotationInstance() throws Exception {
System.out.println(beanDefinetions);
for (BeanDefinetion beanDefinetion : beanDefinetions) {
Class z = Class.forName(beanDefinetion.getType());
singletons.put(beanDefinetion.getId(), z.newInstance());
}
System.out.println(singletons);
}
public void list(File file) throws Exception {
String id = null;
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
list(f);
}
} else {
if (file.getName().endsWith(".class")) {
// System.out.println(file.getName().replace(".class", ""));
String type = getType(file);
Class z = Class.forName(type);
if (z.isAnnotationPresent(YmService.class)) {
Annotation[] annotations = z.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation.annotationType() == YmService.class) {
id = ((YmService) annotation).value();
}
}
BeanDefinetion beanDefinetion = new BeanDefinetion(id, type);
beanDefinetions.add(beanDefinetion);
}
}
}
}
private String getType(File file) {
String path = file.getPath();
path = path.substring(path.indexOf("classes")).replace("classes" + File.separator, "");
return path.replace(File.separator, ".").replace(".class", "");
}
private void injectAnnotationObject() throws Exception {
for (BeanDefinetion beanDefinetion : beanDefinetions) {
PropertyDescriptor[] propertyDescriptors = java.beans.Introspector.getBeanInfo(Class.forName(beanDefinetion.getType())).getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
Method setter = propertyDescriptor.getWriteMethod();
if (setter != null && setter.isAnnotationPresent(YmResource.class)) {
YmResource ymResource = setter.getAnnotation(YmResource.class);
String ref = ymResource.name();
setter.setAccessible(true);
setter.invoke(singletons.get(beanDefinetion.getId()), singletons.get(ref));
}
}
Field[] fields = Class.forName(beanDefinetion.getType()).getDeclaredFields();
for (Field field : fields) {
if (field != null && field.isAnnotationPresent(YmResource.class)) {
YmResource ymResource = field.getAnnotation(YmResource.class);
String ref = ymResource.name();
field.setAccessible(true);
field.set(singletons.get(beanDefinetion.getId()), singletons.get(ref));
}
}
}
}
private void injectObject() throws Exception {
for (BeanDefinetion beanDefinetion : beanDefinetions) {
for (PropertyDefinition propertyDefinition : beanDefinetion.getPropertyDefinitions()) {
PropertyDescriptor[] propertyDescriptors = java.beans.Introspector.getBeanInfo(Class.forName(beanDefinetion.getType())).getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if (propertyDescriptor.getName().equals(propertyDefinition.getName())) {
Method setter = propertyDescriptor.getWriteMethod();
setter.setAccessible(true);
if (propertyDefinition.getValue() == null) {
setter.invoke(singletons.get(beanDefinetion.getId()), singletons.get(propertyDefinition.getName()));
} else {
setter.invoke(singletons.get(beanDefinetion.getId()), propertyDefinition.getValue());
}
}
}
}
}
}
private void parseXML() throws Exception {
SAXReader reader = new SAXReader();
Document doc = reader.read(input);
Map<String, String> ns = new HashMap<String, String>();
ns.put("ns", "http://www.springframework.org/schema/beans");
XPath xpath = doc.createXPath("//ns:beans/ns:bean");
xpath.setNamespaceURIs(ns);
List<Element> elements = xpath.selectNodes(doc);
for (Element element : elements) {
String id = element.attributeValue("id");
String type = element.attributeValue("class");
BeanDefinetion beanDefinetion = new BeanDefinetion(id, type);
beanDefinetions.add(beanDefinetion);
List<Element> propertys = element.selectNodes("property");
for (Element property : propertys) {
String name = property.attributeValue("name");
String ref = property.attributeValue("ref");
String value = property.attributeValue("value");
PropertyDefinition propertyDefinition = new PropertyDefinition(name, ref, value);
beanDefinetion.getPropertyDefinitions().add(propertyDefinition);
}
}
ns = new HashMap<String, String>();
ns.put("context", "http://www.springframework.org/schema/context");
xpath = doc.createXPath("//context:component-scan");
xpath.setNamespaceURIs(ns);
elements = xpath.selectNodes(doc);
System.out.println(elements);
Element element = elements.get(0);
basepcakage = element.attributeValue("base-package");
System.out.println(basepcakage);
try {
Enumeration enumer = ClassLoader.getSystemResources(basepcakage);
while (enumer.hasMoreElements()) {
URL path = (URL) enumer.nextElement();
list(new File(path.getFile()));
}
} catch (IOException ex) {
Logger.getLogger(ClassPathXmlApplicationContext.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void beanInstance() throws Exception {
for (BeanDefinetion beanDefinetion : beanDefinetions) {
Object o = Class.forName(beanDefinetion.getType()).newInstance();
singletons.put(beanDefinetion.getId(), o);
}
}
@Override
public Object getBean(String id) {
return singletons.get(id);
}
}
测试的部分
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context">
<context:component-scan base-package="ym"/>
<bean id="test" class="ym.Test"/>
</beans>
public interface ProductDao {
public void insert();
}
@YmService("productDao")
public class ProductDaoBean implements ProductDao{
public void insert() {
System.out.println("svae............");
}
}
public interface ProductService {
void newProduct();
}
@YmService("productService")
public class ProductServiceBean implements ProductService{
public void newProduct() {
productDao.insert();
System.out.print(name);
}
@YmResource(name="productDao") private ProductDao productDao;
public ProductDao getProductDao() {
return productDao;
}
// @YmResource(name="productDao")
public void setProductDao(ProductDao productDao) {
this.productDao = productDao;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Test {
public static void main(String[] args) {
//ProductService productService=new ProductServiceBean();
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
ProductService productService=(ProductService)ctx.getBean("productService");
productService.newProduct();
}
}