手写SpringIOC注解版本
实体类:
public class User { private Integer id; private String userName; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } } |
自定义注解:
//自定义注解 从Spring容器获取bean @Target({ ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) public @interface ExtResource { } |
// 自定义注解 注入到Spring容器 @Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface ExtService { } |
Service
public interface OrderService { public void addOrder(); } |
@ExtService public class OrderServiceImpl implements OrderService { @Override public void addOrder() { System.out.println("addOrder"); } } |
public interface UserService {
public void add();
} |
//将该类注入到spring容器里面 @ExtService public class UserServiceImpl implements UserService { // 从Spring容器中读取bean @ExtResource private OrderService orderServiceImpl;
public void add() { orderServiceImpl.addOrder(); System.out.println("我是使用反射机制运行的方法"); }
} |
ClassPathXmlApplicationContext
/** * 手写Spring专题 注解版本注入bean * * @author 作者:余胜军 * */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class ClassPathXmlApplicationContext { // 扫包范围 private String packageName; ConcurrentHashMap<String, Object> initBean = null;
public ClassPathXmlApplicationContext(String packageName) { this.packageName = packageName; }
// 使用beanID查找对象 public Object getBean(String beanId) throws Exception { // 1.使用反射机制获取该包下所有的类已经存在bean的注解类 List<Class> listClassesAnnotation = findClassExisService(); if (listClassesAnnotation == null || listClassesAnnotation.isEmpty()) { throw new Exception("没有需要初始化的bean"); } // 2.使用Java反射机制初始化对象 initBean = initBean(listClassesAnnotation); if (initBean == null || initBean.isEmpty()) { throw new Exception("初始化bean为空!"); } // 3.使用beanID查找查找对应bean对象 Object object = initBean.get(beanId); // 4.使用反射读取类的属性,赋值信息 attriAssign(object); return object; }
// 使用反射读取类的属性,赋值信息 public void attriAssign(Object object) throws IllegalArgumentException, IllegalAccessException { // 1.获取类的属性是否存在 获取bean注解 Class<? extends Object> classInfo = object.getClass(); Field[] declaredFields = classInfo.getDeclaredFields(); for (Field field : declaredFields) { // 属性名称 String name = field.getName(); // 2.使用属性名称查找bean容器赋值 Object bean = initBean.get(name); if (bean != null) { // 私有访问允许访问 field.setAccessible(true); // 给属性赋值 field.set(object, bean); continue; } }
}
|