由于本猿本次的目的只有单例生命周期的对象们。
写一个装配仪,遍历原始类型所有声明字段,查看字段的注解,如果有Autowired,就从context里把字段需要的对象设给该字段。
private void autowired(Class c, Object bean) {
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
if (field.getAnnotation(Autowired.class) != null) {
field.setAccessible(true);
String name = field.getName();
ClassInfo ci = classMap.get(name);
ContextType type = ci.getType();
if (type == ContextType.Singleton) {
Object object = singletonMap.get(name);
try {
field.set(bean, object);
} catch (IllegalArgumentException ex) {
Logger.getLogger(Context.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Context.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
遍历singaleMap,将所有对象都取出来,装配所需。
private void wiredSingle() {
for (Map.Entry<String, Object> entrySet : singletonMap.entrySet()) {
String key = entrySet.getKey();
Object value = entrySet.getValue();
autowired(classMap.get(key).getTheClass(), value);
}
}
在loadFromPackage方法末尾加入一行
wiredSingle();
至此为止,三个目标都已实现,我们来测试一下。
Doubi.java
@Component
public class Doubi {
@Autowired
Laowang laowang;
@AopAfter(Duang.class)//再次加特技
@AopBefore(Duang.class)//加特技
public void BeMyDate(String yourName) {
System.out.println(yourName + ":有车吗?");
System.out.println("逗逼:有啊");
System.out.println(yourName + ":宝马还是大奔啊?");
System.out.println("逗逼:三枪……");
System.out.println(yourName + ":衣柜里是谁?");
System.out.println("逗逼:"+laowang.getLaoWangName());
}
}
Laowang.java
@Component
public class Laowang {
public String getLaoWangName(){
return "王尼玛";
}
}
Duang.java
public class Duang extends AopInterceptor{
@Override
public void invoke(Object[] args) {
System.out.println("Duang!Duang!Duang!是头发的特技,是特技的头发!");
}
}
main:
public static void main(String[] args) {
Context context=new Context();
context.loadFromPackage("com.weimo.learn.aop.testobjects");
Doubi doubi=(Doubi) context.getBean("doubi");
doubi.BeMyDate("美女主播");
}
结果:
事实证明,逗逼还是喜欢王尼玛的。