基于反射和注解机制,简单模拟Spring解析Autowired注解的过程。
1、自定义Autowired注解,代码如下
package com.basic.reflect;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.METHOD })
public @interface Autowired {
//注解的name属性
public String name() default "";
}
2、定义相关的业务和Dao类,以及获取Bean的容器(在容器中基于反射实现自动注入)
public class PersonDao {
public int add(Object o) {
System.out.println("dao autowird ok ");
return 0;
}
}
public class ServiceImpl {
@Autowired
private PersonDao personDao;
public int addPerson(Object obj) {
return personDao.add(obj);
}
}
public class BeanContainer {
public static Object getBean(String name) {
try {
Class<?> clazz = Class.forName("com.basic.reflect.ServiceImpl");
Object bean = clazz.newInstance();
Field[] fileds = clazz.getDeclaredFields();
for (Field f : fileds) {
if (f.isAnnotationPresent(Autowired.class)) {
// 基于类型注入
Class<?> c = f.getType();
Object value = c.newInstance();
//允许访问private字段
f.setAccessible(true);
//把引用对象注入属性
f.set(bean, value);
}
}
return bean;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
3、测试类
public class Test {
public static void main(String[] args) {
ServiceImpl impl = (ServiceImpl) BeanContainer.getBean("service");
String name = "test";
impl.addPerson(name);
}
}
总结,上面的代码简单模拟了Spring解析Autowired的过程,写的比较简单,但是精髓已经写到了,主要就是利用反射机制生成实例并且解析注解对其属性进行赋值。其实Spring框架的核心Ioc和Aop的实现,还是利用了java最基本的东西,比如Aop就是利用了动态代理,Ioc就是利用了反射机制