自己动手写SpringMVC(六)

已经分析过DispatcherServlet主要的任务,分为五个任务,任务一:把项目中所有的bean扫描,进行维护,任务二:根据全类名创建bean实例,并进行维护;本篇文章来实现任务三,任务四;

任务三:根据bean进行依赖注入;

	//把service注入到控制层
	public void doIoc(){
		if(beans.entrySet().size()<=0){
			System.out.println("没有一个实例化的类");
			return;
		}
		//遍历实例化的类
		for(Map.Entry<String, Object> entry:beans.entrySet()){
			Object instance = entry.getValue();
			Class<?> clazz = instance.getClass();
			if(clazz.isAnnotationPresent(MyController.class)){
				Field[] fields = clazz.getDeclaredFields();
				for(Field field:fields){
					if(field.isAnnotationPresent(MyAutoWired.class)){
						MyAutoWired auto = field.getAnnotation(MyAutoWired.class);
						String key = auto.value();
						field.setAccessible(true);
						try {
							field.set(instance,beans.get(key));
						} catch (IllegalArgumentException e) {
							e.printStackTrace();
						} catch (IllegalAccessException e) {
							e.printStackTrace();
						}
					}else{
						continue;
					}
				}
			}else{
				continue;
			}	
		}
	}

任务四:方法和地址建立映射关系;

private void buildUrlMapping(){
		if(beans.entrySet().size()<=0){
			System.out.println("没有一个实例化的类");
			return;
		}
		for(Map.Entry<String, Object> entry:beans.entrySet()){
			Object instance = entry.getValue();
			Class<?> clazz = instance.getClass();
			if(clazz.isAnnotationPresent(MyController.class)){
				MyRequestMapping requestMapping = clazz.getAnnotation(MyRequestMapping.class);
				String classPath = requestMapping.value();
				Method[] methods = clazz.getMethods();
				for(Method method:methods){
					if(method.isAnnotationPresent(MyRequestMapping.class)){
						MyRequestMapping methodMapping = method.getAnnotation(MyRequestMapping.class);
						String methodPath = methodMapping.value();
						handlerMap.put(classPath +methodPath, method);
					}else{
						continue;
					}
				}
			}else{
				continue;
			}
		}
	}

这里需要定义一个成员变量,存放地址和映射关系    Map<String,Object> handlerMap = new HashMap<String,Object>();

到此前四个任务都完成了!

猜你喜欢

转载自blog.csdn.net/tangtang1226/article/details/81390141