我们要完成自动装配,那么就要有一个存放bean对象的容器,然后要有装配的注解,那么哪些类该被存到容器呢,在spring中我们使用过@Service、@Resource等,看下面的代码,你也可以做到。
来看看这是一个简单的容器接口
1/** 2 * 容器接口 3 * @author:rex 4 * @create_time:2014-6-26 5 * @version:V1.0 6 */ 7public interface Container { 8 9 Object getBean(String name, BeanType beanType); 10 11 Object getBean(Class<?> type, BeanType beanType); 12 13 Set<?> getBeanNames(); 14 15 Collection<?> getBeans(); 16 17 boolean hasBean(Class<?> clazz); 18 19 boolean hasBean(String name); 20 21 void registBean(Class<?> clazz); 22 23 void initWired(); 24 25}
这个容器提供了基础的存取方法,分别是获取bean对象和注册、是否包含bean,还有一个初始化的方法。
接下来我们来为容器做一个基本的实现。
1import java.lang.reflect.Field; 2import java.lang.reflect.Modifier; 3import java.util.Collection; 4import java.util.HashMap; 5import java.util.Iterator; 6import java.util.Map; 7import java.util.Set; 8 9import com.biezhi.ioc.BeanType; 10import com.biezhi.ioc.Container; 11import com.biezhi.ioc.anntation.Autowired; 12 13/** 14 * 默认的bean容器实现 15 * @author:rex 16 * @create_time:2014-6-26 17 * @version:V1.0 18 */ 19public class DefaultContainerImpl implements Container { 20 21 //存放bean的容器 22 private final Map<String, Object> beansMap = new HashMap<String, Object>(); 23 24 public DefaultContainerImpl() { 25 //初始化加载bean 26 ContainerLoader c = new ContainerLoader(this); 27 c.init(); 28 } 29 30 @Override 31 public Object getBean(String name, BeanType beanType) { 32 try { 33 if(beanType == BeanType.NEW) 34 return Class.forName(name).newInstance(); 35 } catch (Exception e) { 36 e.printStackTrace(); 37 } 38 return beansMap.get(name); 39 } 40 41 @Override 42 public Object getBean(Class<?> type, BeanType beanType) { 43 try { 44 if(beanType == BeanType.NEW) 45 return type.newInstance(); 46 } catch (InstantiationException e) { 47 e.printStackTrace(); 48 } catch (IllegalAccessException e) { 49 e.printStackTrace(); 50 } 51 Iterator<Object> it = this.beansMap.values().iterator(); 52 while(it.hasNext()){ 53 Object obj = it.next(); 54 if(type.isAssignableFrom(obj.getClass())){ 55 return obj; 56 } 57 } 58 return null; 59 } 60 61 @Override 62 public Set<?> getBeanNames(){ 63 return beansMap.keySet(); 64 } 65 66 @Override 67 public Collection<?> getBeans(){ 68 return beansMap.values(); 69 } 70 71 @Override 72 public boolean hasBean(Class<?> clz) { 73 if(null != this.getBean(clz, null)){ 74 return true; 75 } 76 return false; 77 } 78 79 @Override 80 public boolean hasBean(String name){ 81 if(null != this.getBean(name, null)){ 82 return true; 83 } 84 return false; 85 } 86 87 /** 88 * 注册一个bean对象到容器里 89 */ 90 @Override 91 public void registBean(Class<?> clazz){ 92 String name = clazz.getCanonicalName(); 93 try { 94 if(!Modifier.isAbstract(clazz.getModifiers()) && 95 !Modifier.isInterface(clazz.getModifiers())){ 96 Object obj = clazz.newInstance(); 97 beansMap.put(name, obj); 98 } 99 } catch (InstantiationException e) { 100 e.printStackTrace(); 101 } catch (IllegalAccessException e) { 102 e.printStackTrace(); 103 } 104 } 105 106 /** 107 * 初始化注入 108 */ 109 @Override 110 public void initWired(){ 111 Iterator<Object> it = this.beansMap.values().iterator(); 112 try { 113 while(it.hasNext()){ 114 Object obj = it.next(); 115 Field[] fields = obj.getClass().getDeclaredFields(); 116 for(Field field : fields){ 117 Autowired autowired = 118 field.getAnnotation(Autowired.class); 119 if(null != autowired){ 120 //要注入的字段 121 Object wiredField = 122 this.getBean(field.getType(), null); 123 if(null == wiredField){ 124 throw new RuntimeException("Unable to load "+field.getType().getCanonicalName()+"!"); 125 } 126 boolean accessible = field.isAccessible(); 127 field.setAccessible(true); 128 field.set(obj, wiredField); 129 field.setAccessible(accessible); 130 } 131 } 132 } 133 } catch (SecurityException e) { 134 e.printStackTrace(); 135 } catch (IllegalArgumentException e) { 136 e.printStackTrace(); 137 } catch (IllegalAccessException e) { 138 e.printStackTrace(); 139 } 140 } 141}
在构造器里将扫描到的类加载到容器里,然后提供注册bean和获取bean的方法。
1import java.io.File; 2import java.io.FileFilter; 3import java.util.HashSet; 4import java.util.Set; 5 6import com.biezhi.ioc.Container; 7import com.biezhi.ioc.anntation.Service; 8import com.biezhi.ioc.util.ClassHelper; 9 10/** 11 * 加载容器bean 12 * @author:rex 13 * @create_time:2014-6-26 14 * @version:V1.0 15 */ 16public class ContainerLoader { 17 18 private Container container; 19 20 public ContainerLoader(Container container) { 21 this.container = container; 22 } 23 24 public void init(){ 25 //加载要扫描的包,这里可以使用配置文件,我们就默认扫描所有类 26 Set<String> packages = getPackages(); 27 for(String pack : packages){ 28 scanPack(pack); 29 } 30 //初始化注入 31 container.initWired(); 32 } 33 34 private void scanPack(String pack){ 35 Set<Class<?>> classes = ClassHelper.scanPackage(pack); 36 for(Class<?> clazz : classes){ 37 // 这里我只把带有@Service注解的存进去了,你也可以存其他的或者全部 38 Service service = clazz.getAnnotation(Service.class); 39 if(null != service){ 40 //将扫描到的对象保存到容器中 41 container.registBean(clazz); 42 } 43 } 44 } 45 46 /** 47 * 获取当前classes的包名称 48 * @author:rex 49 * @return 50 */ 51 private Set<String> getPackages(){ 52 Set<String> packages = new HashSet<String>(); 53 String appPath = ContainerLoader.class.getResource("/").getPath(); 54 File classDir = new File(appPath); 55 // 如果存在 就获取包下的所有文件 包括目录 56 File[] dirfiles = classDir.listFiles(new FileFilter() { 57 public boolean accept(File file) { 58 return file.isDirectory(); 59 } 60 }); 61 for(File f : dirfiles){ 62 packages.add(f.getName()); 63 } 64 return packages; 65 } 66}
这个类是加载需要的类文件。还有几个代码文件没有贴出来,想看代码的等会打包自己看。
接下来我们看看这个测试,
1@Service 2public class A { 3 4 String name = "菊花"; 5 6 public void say(){ 7 System.out.println("hello, I,m rex !"); 8 } 9} 10 11@Service 12public class B { 13 14 @Autowired 15 private A a; 16 17 private String qq = "3838438"; 18 19 public void hehe(){ 20 a.say(); 21 System.out.println("请问您是" + a.name + "吗?"); 22 } 23 24 public String getQq(){ 25 return this.qq; 26 } 27} 28 29public class Test { 30 31 public static void main(String[] args) { 32 Container c = new DefaultContainerImpl(); 33 c.initWired(); 34 //System.out.println(c.getBeanNames()); 35 B b = (B) c.getBean(B.class, BeanType.SINGLE); 36 b.hehe(); 37 System.out.println(b.getQq()); 38 System.out.println("=================="); 39 B b2 = (B) c.getBean(B.class, BeanType.NEW); 40 b2.hehe(); 41 } 42}
运行结果:
1hello, I,m rex ! 2请问您是菊花吗? 33838438 4================== 5Exception in thread "main" java.lang.NullPointerException 6 at com.biezhi.ioc.test.B.hehe(B.java:15) 7 at com.biezhi.ioc.test.Test.main(Test.java:18)
好了,这样就基本完成了一个简单的ioc自动装配。有喜欢的朋友可以参考代码。点击下载