课堂上讲课时写的一个简单的仿spring框架

框架部分

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();

}
}
编写一个Java项目,模拟一次包括老师备课,同学上课,布置作业和做作业的课堂教学过程。作业为判断字符串是否为2-重复串及其他字符串操作内容 1. 创建Java项目JavaTeaching2012 2. 创建包cn.qtech.util,在其中新建类RepeatedStringEstimator,该类有两个方法:(1)public boolean estimate(String s),用于判断字符串s是不是2-重复串(字符串中每个出现的字符出现2次且仅两次),如判断aaaa不是,abddab是,acbcab是。(2)public void stringOperate(),其中调用适当的字符串操作完成(a)判断两个字符传”abc”和”acb”是否相同,(b)输出"c:\\java\\jsp\\A.java"中第二次出现"\\j"的位置,并输出该位置起到串末的子串 3. 创建包cn.qtech.teaching,在其中新建抽象类UniversityPeople,包含一个抽象方法void doDuty(TeachingMessage msg),表示某人完成自己的任务。 4. 在包cn.qtech.teaching中创建枚举类型TeachingState,其中包括常量BEIKE, TINGKE, BUZHIZUOYE, ZUOZUOYE,分别表示备课,听课,布置作业,做作业 5. 在包cn.qtech.teaching中创建Student类继承自UniversityPeople,该类有成员变量name及name的getter/setter方法。实现的doDuty(TeachingMessage msg)方法中如果判断msg的状态为BEIKE,则修改msg状态为TINGKE并输出:"老师"+msg中老师对象名+"备完课后,去听课!";如果判断msg的状态为BUZHIZUOYE,则修改msg状态为ZUOZUOYE并输出:"老师"+msg中老师对象名+"布置完课作业后,开始做作业!",然后调用RepeatedStringEstimator中的两个方法输出作业结果 6. 在包cn.qtech.teaching中创建Teacher类继承自UniversityPeople,该类有成员变量name及name的getter/setter方法。实现的doDuty(TeachingMessage msg)方法中如果判断msg的状态为TINGKE,则修改msg状态为BUZHIZUOYE并从msg中获得并输出听课学生名单,然后输出
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值