注:以下所有说法都是以单例模式为前提下
代理(CGLIB代理)和拦截器链的实现我的思路可以用下面到图来表述:
这是我的工程目录
在上面的里卖提到了,通过包扫描得到要拦截器以及要提前代理:包扫描已经做成一个工具源代码如下:
package com.mec.util;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public abstract class PackageScanner {
public PackageScanner() {
}
public abstract void dealClass(Class<?> klass);
private void scanPackage(String packageName, File currentFile) {
File[] fileList = currentFile.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
if (pathname.isDirectory()) {
return true;
}
return pathname.getName().endsWith(".class");
}
});
for (File file : fileList) {
if (file.isDirectory()) {
scanPackage(packageName + "." + file.getName(), file);
} else {
String fileName = file.getName().replace(".class", "");
String className = packageName + "." + fileName;
try {
Class<?> klass = Class.forName(className);
if (klass.isAnnotation()
|| klass.isInterface()
|| klass.isEnum()
|| klass.isPrimitive()) {
continue;
}
dealClass(klass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (ExceptionInInitializerError e) {
e.printStackTrace();
}
}
}
}
private void scanPackage(URL url) throws IOException {
JarURLConnection urlConnection = (JarURLConnection) url.openConnection();
JarFile jarFile = urlConnection.getJarFile();
Enumeration<JarEntry> jarEntries = jarFile.entries();
while (jarEntries.hasMoreElements()) {
JarEntry jarEntry = jarEntries.nextElement();
String jarName = jarEntry.getName();
if (jarEntry.isDirectory() || !jarName.endsWith(".class")) {
continue;
}
String className = jarName.replace(".class", "").replaceAll("/", ".");
try {
Class<?> klass = Class.forName(className);
if (klass.isAnnotation()
|| klass.isInterface()
|| klass.isEnum()
|| klass.isPrimitive()) {
continue;
}
dealClass(klass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
public void packageScan(Class<?>[] klasses) {
for (Class<?> klass : klasses) {
packageScan(klass);
}
}
public void packageScan(Class<?> klass) {
packageScan(klass.getPackage().getName());
}
public void packageScan(String[] packages) {
for (String packageName : packages) {
packageScan(packageName);
}
}
public void packageScan(String packageName) {
String packageOpperPath = packageName.replace(".", "/");
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try {
Enumeration<URL> resources = classLoader.getResources(packageOpperPath);
while (resources.hasMoreElements()) {
URL url = resources.nextElement();
if (url.getProtocol().equals("jar")) {
scanPackage(url);
} else {
File file = new File(url.toURI());
if (!file.exists()) {
continue;
}
scanPackage(packageName, file);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
上面的类已在内部实现了对扫描,在使用时候只需要传入要扫描的包并实现public abstract void dealClass(Class<?> klass);即可。通过实行dealClass()就可以得到包下面的每一个class。
在得到每个class后通过检测里面是否有注解来决定时候加入拦截器链或者代理容器。
下面我说下各个注解的作用以及源代码:
@Aspect:
package com.mec.annotation;
/**
* 该注解的作用为,在包扫描的时候如果某个类拥有该注解,则把该类的一个实例对象加到代理容器里面,
* 以后在使用该类的对象的时候直接从容器中得到该类的实例
*/
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.TYPE)
public @interface Aspect {
}
@After:
package com.mec.aop.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 如果有该注解说明这是一个后置拦截器,就需要把他加入到对应到拦截器链中去
* 注解上三个参数的意义
* 1、要拦截的类;
* 2、要拦截的方法
*3、要拦截的方法里面参数类型
*
* @author lixiaotian
*
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface After {
Class<?> klass();
String method();
Class<?>[] parameterTypes();
}
@Before:
package com.mec.aop.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 如果有该注解说明这是一个前置拦截器,就需要把他加入到对应到拦截器链中去
* 注解上两个参数的意义
* 1、要拦截的类;
* 2、要拦截的方法
*
* @author lixiaotian
*
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Before {
Class<?> klass();
String method();
}
@ThrowException:
package com.mec.aop.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*如果有该注解说明这是一个前置拦截器,就需要把他加入到对应到拦截器链中去
* 注解上两个参数的意义
* 1、要拦截的类;
* 2、要拦截的方法
*
* @author lixiaotian
*
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ThrowException {
Class<?> klass();
String method();
}
下面我将所有类的源代码展示出来,并通过里面的注释加以解说:
package com.mec.aop.core;
/**
* 这个类作为一个model,里面储存原对象和代理对象;
*/
public class LxtProxy {
private Object proxyObject;
private Object protoObject;
public LxtProxy() {}
public Object getProxyObject() { return proxyObject; }
public void setProxyObject(Object proxyObject) {
this.proxyObject = proxyObject;
}
public Object getProtoObject() {
return protoObject;
}
public void setProtoObject(Object protoObject) {
this.protoObject = protoObject;
}
}
package com.mec.aop.core;
import com.mec.aop.exception.HaveAlreadyProxyException;
import java.util.HashMap;
import java.util.Map;
/**
* 这个类的作用为一个储存代理容器,
* 通过类名作为键,LxtProxy作为值来储存每一个要代理的对象
*/
public class ProxyFactory {
private static final Map<String,LxtProxy> proxyFactoryMap;
static {
proxyFactoryMap = new HashMap<>();
}
public ProxyFactory() { }
/**
*
* @param className 得到对应的LxtProxy
* @return 返回对应的LxProxy,里面储存代理对象和原对象
*/
public LxtProxy getLxtProxy(String className){
return proxyFactoryMap.get(className);
}
/**
* 存储新的代理对象
* @param className 存储新的
* @param proxy
* @throws Exception 如果Map中已经存在则拋异常
*/
public void SetLxtProxy(String className, LxtProxy proxy) throws Exception{
if(getLxtProxy(className) == null){
proxyFactoryMap.put(className,proxy);
}else {
throw new HaveAlreadyProxyException("代理已存在");
}
}
}
package com.mec.aop.core;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
/**
* 得到IntercepterFactoryList中对应的拦截器链
* 通过对拦截方法的反射进行置前、置后、异常拦截
*/
public class DoIntercepterWork {
private static IntercepterFactory intercepterFactory = new IntercepterFactory();;
public DoIntercepterWork() { }
public boolean dobefore(Class<?> klass, Method method, Object[] args){
IntercepterTargetDefination itd = new IntercepterTargetDefination(klass,method);
List<IntercepterMethodDefination> imdList = intercepterFactory.getBeforeIntercepterList(itd);
if(imdList == null){
return true;
}
boolean result = true;
for(IntercepterMethodDefination methodDefination : imdList){
Method intercepterMethod = methodDefination.getMethod();
Object intercepterObject = methodDefination.getObject();
try {
result = (boolean) intercepterMethod.invoke(intercepterObject,args);
if(result == false){
return false;
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return result;
}
public Object doAfter(Class<?> klass, Method method, Object result){
IntercepterTargetDefination itd = new IntercepterTargetDefination(klass,method);
List<IntercepterMethodDefination> imdList = intercepterFactory.getAfterIntercepterList(itd);
if(imdList == null){
return result;
}
return result;
}
public void doException(Class<?> klass, Method method, Throwable throwable){
IntercepterTargetDefination itd = new IntercepterTargetDefination(klass,method);
List<IntercepterMethodDefination> imdList = intercepterFactory.getExceptionIntercepterList(itd);
if (imdList == null){
return;
}
for (IntercepterMethodDefination methodDefination : imdList){
Class<?> intercepterClass = methodDefination.getKlass();
Method intercepterMethod = methodDefination.getMethod();
try {
intercepterMethod.invoke(intercepterClass, throwable);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
package com.mec.aop.core;
import java.lang.reflect.Method;
/**
* 描述拦截器方法的地方在之后的拦截的时候要通过反射调用
*/
public class IntercepterMethodDefination {
private Class<?> klass;
private Method method;
private Object object;
public IntercepterMethodDefination() {
}
public IntercepterMethodDefination(Class<?> klass, Method method, Object object) {
this.klass = klass;
this.method = method;
this.object = object;
}
public Class<?> getKlass() {
return klass;
}
public void setKlass(Class<?> klass) {
this.klass = klass;
}
public Method getMethod() {
return method;
}
public void setMethod(Method method) {
this.method = method;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
}
package com.mec.aop.core;
import java.lang.reflect.Method;
import java.util.Objects;
/**
* 描述要被拦截的类的方法,并作为得到List<IntercepterMethodDefination>的键
* 覆盖hashCode()和equals()方法是为在Map<IntercepterTargetDefination, List<IntercepterMethodDefination>>
* get()的时候由于两个IntercepterTargetDefination是不同的实例对象,而里面的klass和method是一样,得到对应的List<>
* 不覆盖是通过地址get()得不到List<>
*
*/
public class IntercepterTargetDefination {
private Class<?> klass;
private Method method;
public IntercepterTargetDefination(Class<?> klass, Method method) {
this.klass = klass;
this.method = method;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IntercepterTargetDefination that = (IntercepterTargetDefination) o;
return Objects.equals(klass, that.klass) &&
Objects.equals(method, that.method);
}
@Override
public int hashCode() {
return Objects.hash(klass, method);
}
}
package com.mec.aop.core;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 存储拦截器的地方,将要拦截的方法的描述作为键,具体的拦截器形成一个拦截器链
* 存储起来
*/
public class IntercepterFactory {
private static final Map<IntercepterTargetDefination, List<IntercepterMethodDefination>> beforeMap;
private static final Map<IntercepterTargetDefination, List<IntercepterMethodDefination>> afterMap;
private static final Map<IntercepterTargetDefination, List<IntercepterMethodDefination>> exceptionMap;
static {
beforeMap = new HashMap<>();
afterMap = new HashMap<>();
exceptionMap = new HashMap<>();
}
private static void addIntercepter(Map<IntercepterTargetDefination, List<IntercepterMethodDefination>> map,
IntercepterTargetDefination itd,IntercepterMethodDefination imd
){
List<IntercepterMethodDefination> IntercepterMethodList = map.get(itd);
if(IntercepterMethodList== null){
IntercepterMethodList = new ArrayList<>();
map.put(itd,IntercepterMethodList);
}
IntercepterMethodList.add(imd);
}
public static void addBeforeIntercepter(IntercepterTargetDefination itd,IntercepterMethodDefination imd){
addIntercepter(beforeMap,itd,imd);
}
public static void addAfterIntercepter(IntercepterTargetDefination itd,IntercepterMethodDefination imd){
addIntercepter(afterMap,itd,imd);
}
public static void addExceptionIntercepter(IntercepterTargetDefination itd,IntercepterMethodDefination imd){
addIntercepter(exceptionMap,itd,imd);
}
public List<IntercepterMethodDefination> getBeforeIntercepterList(IntercepterTargetDefination itd){
return beforeMap.get(itd);
}
public List<IntercepterMethodDefination> getAfterIntercepterList(IntercepterTargetDefination itd){
return afterMap.get(itd);
}
public List<IntercepterMethodDefination> getExceptionIntercepterList(IntercepterTargetDefination itd){
return exceptionMap.get(itd);
}
}
package com.mec.aop.core;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
/**
* 这是核心的一个类,我来解释每个方法
*/
public class ProxyBulid {
private LxtProxy lxtproxy = null;
private DoIntercepterWork doIntercepterWork = new DoIntercepterWork();
public ProxyBulid() {
}
/**
*
* @param klass 在包扫描的时候,如果某个类有@Aspect()会调用这个方法,这个方法会吊用getProxy()方法
* @throws Exception
*/
public void creatProxy(Class<?> klass) throws Exception {
getProxy(klass);
}
/**
*
* @param klass 这个方法的主要作用是:
* 1、判断传过来的类是否生成的代理;
* 2.1、如果没有,则生成一个新的lxtProxy,并调用cglibProxy()生成代理,
* 并将代理和原对象储存起来,并加入对应容器中
* 2.2、如果有,不做啥
* 3、返回代理对象
* @return
* @throws Exception
*/
public Object getProxy(Class<?> klass) throws Exception {
ProxyFactory proxyFactory = new ProxyFactory();
lxtproxy = proxyFactory.getLxtProxy(klass.getName());
Object proxyObject = null;
if(lxtproxy == null){
lxtproxy = new LxtProxy();
Object protoObject = klass.newInstance();
proxyObject = cglibProxy(protoObject,klass);
lxtproxy.setProtoObject(protoObject);
lxtproxy.setProxyObject(proxyObject);
proxyFactory.SetLxtProxy(klass.getName(),lxtproxy);
}
return lxtproxy.getProxyObject();
}
/**
*
* @param object
* @param klass 生成代理对象,并实现intercept()方法。在里面调用doInvoker()
* @return 代理对象
*/
public Object cglibProxy(Object object,Class<?> klass){
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(klass);
MethodInterceptor methodInterceptor = new MethodInterceptor() {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
return doInvoker(klass,object,method,args);
}
};
enhancer.setCallback(methodInterceptor);
return enhancer.create();
}
/**
*
* @param klass 执行在反射调用原对象应该执行的方法前,
* 调用doIntercepterWork中dobefore()来执行对应List中前拦截器链的所用方法
* ,如果用一次方法flase则,不继续执行
* 如果返回true,则反射调用原对象应该执行的方法
* 再调用doIntercepterWork中ddoAfter()来执行对应List中后拦截器链的所用方法
* 如果上面发生异常则调用doIntercepterWork中ddoException()来执行对应List中异常拦截器链的所用方法
* @param object
* @param method
* @param args
* @return
* @throws Throwable
*/
private Object doInvoker(Class<?> klass, Object object, Method method, Object[] args) throws Throwable{
Object result = null;
// 前置拦截
if (doIntercepterWork.dobefore(klass, method, args) == false) {
return null;
}
try {
result = method.invoke(object, args);
// 后置拦截
doIntercepterWork.doAfter(klass, method, result);
} catch (Throwable e) {
// 异常拦截
e.printStackTrace();
doIntercepterWork.doException(klass, method, e);
throw e;
}
return result;
}
}
package com.mec.aop;
import com.mec.annotation.Aspect;
import com.mec.aop.annotation.After;
import com.mec.aop.annotation.Before;
import com.mec.aop.annotation.ThrowException;
import com.mec.aop.core.IntercepterFactory;
import com.mec.aop.core.IntercepterMethodDefination;
import com.mec.aop.core.IntercepterTargetDefination;
import com.mec.aop.core.ProxyBulid;
import com.mec.aop.exception.WrongReturnTypeForIntercepterException;
import com.mec.util.PackageScanner;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
/**
* 该类的主要整个之前的所有类使其联系起来
*/
public class BulidingFactoy {
private static ProxyBulid proxyBulid = new ProxyBulid();
public BulidingFactoy() { }
/**
* 传过来需要生成代理的包名,以及拦截器所在的包名
* 调用扫描两个包
* @param proxyPackageName
* @param IntercepterPackageName
*/
public static void scanPackage(String proxyPackageName,String IntercepterPackageName){
scanProxyPackage(proxyPackageName);
scanIntercepterPackage(IntercepterPackageName);
}
public static void scanProxyPackage(String proxyPackageName){
new PackageScanner() {
@Override
public void dealClass(Class<?> klass) {
System.out.println(klass.isAnnotationPresent(Aspect.class));
if(klass.isAnnotationPresent(Aspect.class)){
try {
proxyBulid.creatProxy(klass);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.packageScan(proxyPackageName);
}
public static void scanIntercepterPackage(String IntercepterPackageName){
new PackageScanner() {
@Override
public void dealClass(Class<?> klass) {
try {
Object intercepterObject = klass.newInstance();
Method[] intercepterMethods = klass.getDeclaredMethods();
for (Method intercepterMethod :intercepterMethods){
if(intercepterMethod.isAnnotationPresent(Before.class)){
Before before = intercepterMethod.getAnnotation(Before.class);
dealBeforeInterceptor(klass,intercepterObject,intercepterMethod,before);
} else if (intercepterMethod.isAnnotationPresent(After.class)) {
After after = intercepterMethod.getAnnotation(After.class);
dealAfterInterceptor(klass,intercepterObject,intercepterMethod,after);
}else if(intercepterMethod.isAnnotationPresent(ThrowException.class)){
ThrowException throwException = klass.getAnnotation(ThrowException.class);
dealExceptionInterceptor(klass,intercepterObject,intercepterMethod,throwException);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.packageScan(IntercepterPackageName);
}
/**
* 如果在扫描包时候发现某类有@Before注解,对其进行处理,把他加入到拦截器链
* @param interceptorClass 拦截器方法所在的类
* @param interceptorObject 拦截器方法
* @param interceptorMethod 拦截器方法的对象
* @param before 注解的值
* @throws WrongReturnTypeForIntercepterException
* @throws NoSuchMethodException
*/
private static void dealBeforeInterceptor(Class<?> interceptorClass, Object interceptorObject,
Method interceptorMethod, Before before) throws WrongReturnTypeForIntercepterException, NoSuchMethodException {
Class<?> returnType = interceptorMethod.getReturnType();
if(returnType != boolean.class){
throw new WrongReturnTypeForIntercepterException("前置拦截器("
+ interceptorMethod + ")返回值类型只能是boolean");
}
Class<?> targetKlass = before.klass();
Method targetMethod = targetKlass.getMethod(before.method(),
interceptorMethod.getParameterTypes());
IntercepterMethodDefination imd = new IntercepterMethodDefination(interceptorClass,interceptorMethod,interceptorObject);
IntercepterTargetDefination itd = new IntercepterTargetDefination(targetKlass,targetMethod);
IntercepterFactory.addBeforeIntercepter(itd,imd);
}
/**
* 如果在扫描包时候发现某类有@After注解,对其进行处理,把他加入到拦截器链
* @param interceptorClass 拦截器方法所在的类
* @param interceptorObject 拦截器方法
* @param interceptorMethod 拦截器方法的对象
* @param after 注解的值
* @throws WrongReturnTypeForIntercepterException
* @throws NoSuchMethodException
*/
private static void dealAfterInterceptor(Class<?> interceptorClass, Object interceptorObject,
Method interceptorMethod, After after) throws WrongReturnTypeForIntercepterException, NoSuchMethodException {
Class<?> returnType = interceptorMethod.getReturnType();
if(returnType != Object.class){
throw new WrongReturnTypeForIntercepterException("前置拦截器("
+ interceptorMethod + ")返回值类型只能是Object");
}
Class<?> targetKlass = after.klass();
Method targetMethod = targetKlass.getMethod(after.method(),
interceptorMethod.getParameterTypes());
IntercepterMethodDefination imd = new IntercepterMethodDefination(interceptorClass,interceptorMethod,interceptorObject);
IntercepterTargetDefination itd = new IntercepterTargetDefination(targetKlass,targetMethod);
System.out.println(itd);
IntercepterFactory.addAfterIntercepter(itd,imd);
}
/**
* 如果在扫描包时候发现某类有@ThrowException注解,对其进行处理,把他加入到拦截器链
* @param interceptorClass 拦截器方法所在的类
* @param interceptorObject 拦截器方法
* @param interceptorMethod 拦截器方法的对象
* @param e 要拦截的异常
* @throws WrongReturnTypeForIntercepterException
* @throws NoSuchMethodException
*/
private static void dealExceptionInterceptor(Class<?> interceptorClass, Object interceptorObject,
Method interceptorMethod, ThrowException e) throws WrongReturnTypeForIntercepterException, NoSuchMethodException {
Class<?> returnType = interceptorMethod.getReturnType();
if(returnType != void.class){
throw new WrongReturnTypeForIntercepterException("前置拦截器("
+ interceptorMethod + ")返回值类型只能是void");
}
Class<?> targetKlass = e.klass();
Method targetMethod = targetKlass.getMethod(e.method(),
interceptorMethod.getParameterTypes());
IntercepterMethodDefination imd = new IntercepterMethodDefination(interceptorClass,interceptorMethod,interceptorObject);
IntercepterTargetDefination itd = new IntercepterTargetDefination(targetKlass,targetMethod);
IntercepterFactory.addExceptionIntercepter(itd,imd);
}
/**
*
* @param klass 为其他类提供得到某个类得到代理的方法
* @return 如果发现这个类在容器中已经有,直接返回代理。
* 没有则新生成以及并且存储到容器中并返回代理对象
* @throws Exception
*/
public static Object getProxy(Class<?> klass) throws Exception {
return proxyBulid.getProxy(klass);
}
}
综上就是我这个工程的代码和思路。