1. 自定义注解
- 类级别的注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtService {
}
- 属性级别的注解
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtAutowired {
}
2. 指定扫描的package,得到包下的class List
具体的实现可以直接参考Spring源码(不重要)
//获取该包名下的class
List<Class<?>> classes = ClassUtil.getClasses(packageName);
3. 找到添加了注解的bean,并把实例存储到map中
public ConcurrentHashMap<String, Object> findClassExistAnnotation(List<Class<?>> classes) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
for (Class<?> clazz : classes) {
ExtService annotation = clazz.getAnnotation(ExtService.class);
if (annotation != null) {
String className = clazz.getSimpleName();
Object obj = newInstance(clazz.getName(), new HashMap<>());
beans.put(toLowerCaseFirstOne(className), obj);
continue;
}
}
return beans;
}
4. 为实例添加依赖注解类
/**
* 依赖注入
*/
public void attributeAssign(Object obj) throws IllegalAccessException {
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
ExtAutowired autowired = field.getAnnotation(ExtAutowired.class);
if (autowired != null) {
String fieldName = field.getName();
//获取到依赖注入的bean
Object bean = beans.get(fieldName);
if (bean != null) {
field.setAccessible(true);
field.set(obj, bean);
}
}
}
}
给bean添加依赖注解
annotionBeans.entrySet().stream().forEach(entry -> {
try {
attributeAssign(entry.getValue());
} catch (IllegalAccessException e) {
e.printStackTrace();
}
});
网友评论