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