从零实现MVC框架之依赖注入IOC(7)

我们的目的是在学习MVC的实现方式,而不是真的做一个MVC框架,所以就一切从简,所以这里我们只做Controller中的依赖注入。

也就是说只有Controller中才可以使用我们下面创建的Inject注解。如果再其他的地方使用是注入不成功的哦。

注解

package com.hc.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * 
 * @author chuer
 * @date 2014-7-16 下午4:34:14
 * @version V1.0
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface Inject {

	public String className();
}


修改AbstractHcAction

			Class<?> cls = controllerClassInfo.getCls();
			Object newInstance = cls.getConstructor(new Class[]{}).newInstance(new Object[]{});
			
			//依赖注入
			Field[] declaredFields = cls.getDeclaredFields();
			for(Field field : declaredFields){
				if(field.isAnnotationPresent(Inject.class)){
					Inject inject = field.getAnnotation(Inject.class);
					String setMethod = "set"+field.getName().substring(0,1).toUpperCase()+field.getName().substring(1);
					Class<?> forName = Class.forName(inject.className());
					Object newInstance2 = forName.getConstructor(new Class[]{}).newInstance(new Object[]{});
					Object newInstance3 = TransactionProxyCache.cache.get(forName);
					if(newInstance3 != null){
						newInstance2 = newInstance3;
					}
					Method method = cls.getMethod(setMethod, newInstance2.getClass().getInterfaces());
					method.invoke(newInstance, new Object[]{newInstance2});
				}
			}
			
			//调用controller方法
			Method method = controllerClassInfo.getMethodMap().get(methodParam);


修改UserController

	@Inject(className="com.hc.sample.service.UserServiceImpl")
	private UserService userService;


测试

请看第6章的测试方法。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值