抽象依赖原则的使能工具God、Spring DI模块并不需要太多术语来介绍,IoC容器与IoC一毛钱的关系都没有。本节用最简单的代码说明:①Java注解取代配置文件;②容器与注入。最简单的代码在于说明问题的本质,该代码将有很多的不足。
1.Java注解取代配置文件
https://zhuanlan.zhihu.com/p/343826810
package chap3.init.godplus;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Inject {
String value() default "";
}
package chap3.init.godplus;
import java.lang.annotation.*;
import java.lang.reflect.*;
public class God0 {
private God0() { }
/**
* 解析clazz 的类中的@Inject(typeName),按照typeName指定的类全名创建对象。
*
* @param clazz 含有@Inject的类
* @return Inject标记的对象
*/
public static Object create(Class<?> clazz) {
Object r = null;
//不支持多个@Inject
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
Annotation[] annotations = field.getDeclaredAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof Inject) {
Inject inj = (Inject) annotation;
String typeName = inj.value();
try {
r = Class.forName(typeName).newInstance();
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
}
}
}
}
return r;
}
} package chap3.init;
public class Mom implements IWoman {
@Override public void say() {
System.out.println("Mom say...");
}
}
package chap3.init;
import chap3.init.godplus.God0;
import chap3.init.godplus.Inject;
public class Boy{
@Inject("chap3.init.Mom") private final IWoman mom;
//@Inject("chap3.init.Wife") private final IWoman wife;
public Boy(){
mom = (IWoman)God0.create(Boy.class) ;
}
public void say(){
mom.say();
System.out.println("Boy say....");
}
}
//Demo
public static void testGod() {//
Boy boy = new Boy();
boy.say();
}
使用配置文件的缺点,主要是源代码和配置文件的联动问题。例如重构类的名字后,就必须到相应的配置文件中手工修改对应的字符串;或者在编写一些测试代码时,需要在源代码和配置文件之间跑来跑去。
4.如果...
public @interface Inject{
String typeName();
int id() default 0;
}
HelloWorld调用的解析方法create(Object obj,int id)时,将增加的属性作为参数。
package creational.di.annotationDemo;
import principle.IServer;
import tool.God;
import tool.Init;
/**
* 多个@Init
*
* @author (yqj2065)
* @version (0.1)
*/
public class HelloWorld{
@tool.Init1("principle.Server") private IServer s0;
@Init(typeName="principle.Server") private IServer s1;
@Init(typeName="principle.S2",id=1) private IServer s2;
@Init(typeName="principle.S2",id=1) private IServer s3;
public HelloWorld()throws Exception{
s0 = (IServer)God.init1(this) ;
}
public static void main(String[] args)throws Exception{
HelloWorld client = new HelloWorld();
client.s0.foo();
client.s1 = (IServer)God.create(client) ;//id=0
client.s1.foo();
client.s2 = (IServer)God.create(client,1) ;client.s2.foo();
client.s3 = (IServer)God.create(client,1) ;client.s3.foo();
}
}
输出:
Server.foo()
Server.foo()
S2.foo()
S2.foo()
Server.foo()
S2.foo()
S2.foo()