目的
仅限于练习注解和反射以及代理的使用。
实现
容器加载以及测试类
/**
* @author : hongbo.liu
* @date : 15:06 2022/7/27
* 自定义IOC容器
* 1,扫描指定包中的全限定类名(不支持扫描jar包中的class)
* 2,获取需要进行增强的自定义注解名称
* 3,创建bean并缓存,此处需要校验是否需要创建代理对象(扫描类方法的注解,如果包含aop的注解则需要创建代理对象)
* 4,依赖注入,如果class对象的属性有注入的注解,则需要为其赋值,从bean map中获取,如果没有,则递归执行步骤 3
*/
public class CustomizeIocContainer {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
//1,扫描指定的包,获取类全限定类名
List<Class<?>> classes = ClassPathUtil.getClasses("aop");
//2,获取指定注解的类中代理的方法信息
ProxyBeanHandler.getProxyMethodByAnnotation(classes);
//3,如果不需要生成代理,则直接通过反射将类对象缓存,否则,生成代理对象缓存
ProxyBeanHandler.createProxyBean(classes);
//从bean map中获取实例测试
ProxyTest proxyTest = (ProxyTest) ProxyBeanHandler.beanMap.get("proxyTest");
proxyTest.proxyTest();
}
}
获取指定包下的全限定类名
/**
* @author : hongbo.liu
* @date : 16:22 2022/7/27
* <p>
* 获取指定包下类的权限的类名
*/
public class ClassPathUtil<T> {
public static volatile List<String> classPaths = new ArrayList<String>();
//先把包名转换为路径,首先得到项目的classpath
public static volatile String classpath = Main.class.getResource("/").getPath();
//包名basePageName转换为路径名
public static final String basePageName = "aop".replace(".", File.separator);
public static final String finalBasePageName = basePageName;
public static synchronized List<Class<?>> getClasses(String basePageName) {
//classpath和basePageName合并
String searchPath = (classpath + basePageName).replace("test-classes", "classes");
//获取指定包下全限定类名
doPath(new File(searchPath));
//筛选出符合条件的class对象
return filterClass().apply(classPaths);
}
/**
* 递归获取class文件 将类的绝对路径写入到classPaths中
* @param file
*/
private static synchronized void doPath(File file) {
if (file.isDirectory()) {
//递归文件夹
File[] files = file.listFiles();
Arrays.stream(files).forEach(item ->{doPath(item);});
} else {
//获取class文件
if (file.getName().endsWith(".class")) {
classPaths.add(file.getPath());
}
}
}
/**
* 过滤符合要求的class对象
* @return
*/
public static synchronized Function<List<String>, List<Class<?>>> filterClass() {
List<Class<?>> classes = new ArrayList();
return new Function<List<String>, List<Class<?>>>() {
@SneakyThrows
@Override
public List<Class<?>> apply(List<String> strings) {
classPaths.stream().forEach(new Consumer<String>() {
@SneakyThrows
@Override
public void accept(String s) {
s = s.replace(classpath.replace("/", "\\").replaceFirst("\\\\", ""), "").replace("\\", ".").replace(".class", "");
int beg = s.indexOf(finalBasePageName + ".");
Class<?> aClass = Class.forName(s.substring(beg, s.length()));
// 过滤出带@MyService和@MyAspect注解的类
if (aClass.getAnnotation(MyService.class) != null || aClass.getAnnotation(MyAspect.class) != null) {
classes.add(aClass);
}
}
});
return classes;
}
};
}
}
生成代理对象完成依赖注入并存入缓存
/**
* @author : hongbo.liu
* @date : 16:27 2022/7/27
* 类注解过滤
*/
public class ProxyBeanHandler {
public static Map<String, Object> beanMap = new HashMap<>();
public static Map<String, Map<String, String>> proxyMethod = new HashMap<>();
public static Map<String, Object> createProxyBean(List<Class<?>> classes) {
classes.stream().forEach(item -> {
if (item.getAnnotation(MyService.class) != null) {//过滤出带@MyService注解的类
if (item.getInterfaces().length > 0) {
try {
Object obj = item.newInstance();
String className = obj.getClass().getInterfaces()[0].getSimpleName();
String beanName = className.substring(0, 1).toLowerCase() + className.substring(1, className.length());
//如果bean已经存在则不需要创建,跳出本次循环
if (beanMap.containsKey(beanName)) return;
//依赖注入
dependencyInjection(obj);
//增强切入点,将代理对象缓存到map
enhancementPoint(obj, beanName);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
});
return beanMap;
}
/**
* 增强代理方法,并将代理对象存入map中
*
* @param obj
* @param beanName
*/
private static void enhancementPoint(Object obj, String beanName) {
//获取包含Aop的注解
Method[] declaredMethods = obj.getClass().getDeclaredMethods();
if (proxyMethod != null && proxyMethod.size() > 0) {
Arrays.stream(declaredMethods).forEach(
item -> {
Annotation[] annotations = item.getAnnotations();
if (annotations.length > 0) {
Arrays.stream(annotations).forEach(one -> {
if (proxyMethod.containsKey(one.annotationType().getSimpleName())) {
//子类实现接口不为空,则生成基于JDK代理对象
Class<?>[] interfaces = obj.getClass().getInterfaces();
if (interfaces != null && interfaces.length > 0) {
Object proxyObject = null;
try {
proxyObject = new ProxyFactory().createProxy(obj, Class.forName(proxyMethod.get(one.annotationType().getSimpleName()).get(AopEnum.ASPECT_ANNOTATION_KEY.getKey())).newInstance());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
beanMap.put(beanName, proxyObject);
}
}
});
}
}
);
}
//如果bean方法没有增强注解,则生成普通代理对象(此处可以改为普通对象obj)
if (beanMap.get(beanName) == null) {
//生成代理对象
Object proxyObject = new ProxyFactory().createProxy(obj, new Object());
beanMap.put(beanName, proxyObject);
}
}
/**
* 递归给属性注入依赖
* @param obj
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException
*/
private static void dependencyInjection(Object obj) {
//给obj带@MyAutowired注解的属性注入依赖(代理对象)
Field[] declaredFields = obj.getClass().getDeclaredFields();
Arrays.stream(declaredFields).forEach(field -> {
Annotation[] declaredAnnotations = field.getDeclaredAnnotations();
Arrays.stream(declaredAnnotations).forEach(annotation -> {
//有@MyAutowired注解
if (annotation.annotationType().getTypeName().equals(MyAutowired.class.getTypeName())) {
//将代理map中的代理对象设置给当前属性
Object proxyBean = ProxyBeanHandler.beanMap.get(field.getName());
//如果从bean集合中获取的对象为空,则创建该对象,并放入代理map缓存中
if (proxyBean == null) {
Set<Class<?>> sonClassSet = getSonClassInstances(field.getType());
//默认第一个接口的子类class对象
List<Class<?>> sunClass = new ArrayList<>();
if (!CollectionUtils.isEmpty(sonClassSet)) sunClass.add(sonClassSet.iterator().next());
//递归调用createProxyBean完成依赖注入
ProxyBeanHandler.createProxyBean(sunClass);
//再次从beanMap获取,如果获取不到则报错提示
proxyBean = ProxyBeanHandler.beanMap.get(field.getName());
if (proxyBean == null)
throw new RuntimeException("create " + obj.getClass().getSimpleName() + "proxy bean error ," + field.getName() + "bean is not find");
}
try {
field.set(obj, proxyBean);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
});
});
}
/**
* 获取需要增强的方法上面的注解
*
* @param classes
* @return
* @throws ClassNotFoundException
*/
public static void getProxyMethodByAnnotation(List<Class<?>> classes) {
classes.forEach(item -> {
try {
//获取指定注解的class对象
if (item.getAnnotation(MyAspect.class) != null) {
Method[] declaredMethods = item.getDeclaredMethods();
Arrays.stream(declaredMethods).forEach(method -> {
if (method.getAnnotation(MyPointcut.class) != null) {
Map map = new HashMap();
map.put(AopEnum.ASPECT_ANNOTATION_KEY.getKey(), item.getTypeName());
proxyMethod.put(method.getAnnotation(MyPointcut.class).value(), map);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
});
}
/**
* 获取子类class对象
*
* @param supClass
* @return
*/
private static Set<Class<?>> getSonClassInstances(Class supClass) {
String aPackage = ClassUtil.getPackage(supClass);
Set<Class<?>> classes = ClassUtil.scanPackage(aPackage);
Set<Class<?>> collect = classes.stream().filter(sonClass -> {
boolean allAssignableFrom = ClassUtil.isAllAssignableFrom(new Class[]{supClass},
new Class[]{sonClass});
//将本身排除
return allAssignableFrom && sonClass != supClass;
}).collect(Collectors.toSet());
return collect;
}
}
代理工厂
/**
* @author : hongbo.liu
* @date : 17:14 2022/7/27
* 代理工厂,对指定注解的方法进行代理
* target 被代理的对象
* point用于增强方法的对象
*/
public class ProxyFactory implements InvocationHandler {
Object target;//被代理的对象
Object point;//代理方法切入点
public Object createProxy(Object target, Object point) {
this.target = target;
this.point = point;
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return handleProxyMethod(method, args);
}
/**
* 处理代理方法
* @param method
* @param args
* @return
* @throws IllegalAccessException
* @throws InstantiationException
* @throws InvocationTargetException
*/
public Object handleProxyMethod(Method method, Object[] args) throws IllegalAccessException, InstantiationException, InvocationTargetException {
//如果代理对象执行的方法和目标对象的方法名称一样,参数列表一样,并且目标对象的方法上有@MyAop注解,则需要对该方法进行增强
Method[] targetDeclaredMethods = target.getClass().getDeclaredMethods();
for (Method targetMethod : targetDeclaredMethods) {
if (containAnnotation(targetMethod.getDeclaredAnnotations()) && method.getName().equals(targetMethod.getName())) {
Class<?>[] parameterTypes = method.getParameterTypes();
Class<?>[] targetParameterTypes = targetMethod.getParameterTypes();
boolean isPoint = parameterTypes.length == targetParameterTypes.length && targetParameterTypes.length == 0;
if (parameterTypes.length == targetParameterTypes.length && targetParameterTypes.length != 0) {//参数个数一样
for (int i = 0; i < parameterTypes.length; i++) {//校验参数类型是否一致
if (!parameterTypes[i].getTypeName().equals(targetParameterTypes[i].getTypeName())) {//如果有一个参数类型不一致,则为重载的方法,不能做增强
isPoint = false;
}
}
}
//如果方法名称一样,参数列表也一样,则做增强
if (isPoint) {
//增强类的方法列表
Method[] declaredMethods = point.getClass().getDeclaredMethods();
//实例化增强类对象
Object obj = point.getClass().newInstance();
for (Method md : declaredMethods) {
//找到增强类的具体增强方法,将被增强的方法、对象、参数传递进去
if (md.getAnnotation(MyPointcut.class) != null) {
return md.invoke(obj, new Object[]{method, target, args});
}
}
}
}
}
//不含@MyAop注解的方法则不走代理
return method.invoke(target, args);
}
/**
* 判断方法的注解是否包含@MyAop
*
* @param declaredAnnotations
* @return
*/
private boolean containAnnotation(Annotation[] declaredAnnotations) {
boolean isContain = false;
for (Annotation declaredAnnotation : declaredAnnotations) {
if (declaredAnnotation.annotationType().getSimpleName().equals(MyAop.class.getSimpleName())) {
isContain = true;
break;
}
}
return isContain;
}
}
注解类
/**
* @author : hongbo.liu
* @date : 17:03 2022/7/27
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAop {
}
/**
* @author : hongbo.liu
* @date : 16:45 2022/7/27
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAspect {
String value() default "";
}
/**
* @author : hongbo.liu
* @date : 14:56 2022/7/28
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAutowired {
String value() default "";
}
/**
* @author : hongbo.liu
* @date : 16:49 2022/7/27
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Service
public @interface MyPointcut {
String value() default "";
}
/**
* @author : hongbo.liu
* @date : 16:35 2022/7/27
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyService {
/**
* bean名称
* @return
*/
String value() default "";
}
枚举
/**
* @author : hongbo.liu
* @date : 10:00 2022/8/8
*/
public enum AopEnum {
/**
* 自定义增强注解key
*/
ASPECT_ANNOTATION_KEY("class");
private String key;
AopEnum(String key) {
this.key = key;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
切面
/**
* @author : hongbo.liu
* @date : 17:03 2022/7/27
*/
@MyAspect
public class ServiceAspect {
@MyPointcut("MyAop")
public Object serviceAspect(Method method, Object target, Object[] args) throws InvocationTargetException, IllegalAccessException {
System.out.println("方法执行前..............");
method.invoke(target, args);
System.out.println("方法执行后..............");
return null;
}
}
测试接口
/**
* @author : hongbo.liu
* @date : 17:14 2022/7/28
*/
public interface ProxyTest {
void proxyTest();
}
测试接口实现类
/**
* @author : hongbo.liu
* @date : 17:09 2022/7/28
*/
@MyService
public class ProxyTestImpl implements ProxyTest {
@MyAutowired
public TestService testService;
public void proxyTest(){
testService.get();
}
}