加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 22:48:26 所属栏目:百科 来源:网络整理
导读:我们的目的是在学习MVC的实现方式,而不是真的做一个MVC框架,所以就一切从简,所以这里我们只做Controller中的依赖注入。 也就是说只有Controller中才可以使用我们下面创建的Inject注解。如果再其他的地方使用是注入不成功的哦。 注解 package com.hc.annot

我们的目的是在学习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章的测试方法。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读