com.ajaxjs.ioc.aop.Aop Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of ajaxjs-base Show documentation
Show all versions of ajaxjs-base Show documentation
A pure Java library that provides many tools, utils, and functions.
/**
* Copyright Sp42 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ajaxjs.ioc.aop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Objects;
/**
* AOP 抽象类
*
* @author sp42 [email protected]
* @param T 必须是目标对象的其中一个接口类型
*/
public class Aop implements InvocationHandler {
/**
* 原目标对象,未被 AOP 包装过的
*/
private T target;
private AopHandler[] handlers;
/**
* 对目标对象进行 AOP 处理,AOP所在的模块,就是本类!
*
* @param target 目标对象,被 AOP 接管的对象
* @return AOP 代理对象,已经不是原来目标对象了,但是同一接口的
*/
/**
*
* @param target
* @param handlers 绑定多个代理处理器
* @return
*/
@SuppressWarnings("unchecked")
public T bind(T target, AopHandler... handlers) {
Objects.toString(target, "proxy 对象不能为空!");
this.target = target;
this.handlers = handlers;
Object obj = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),
this);
return (T) obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
for (AopHandler handler : handlers) {
Object beforeReturn = handler.before(target, method, method == null ? null : method.getName(), args);
if (beforeReturn instanceof ReturnBefore)
return ((ReturnBefore) beforeReturn).getReturnValue(); // 中止运行 aop
// 如果作为参数
boolean isBeforeReturn = beforeReturn != null && beforeReturn instanceof ReturnAsArg;
if (isBeforeReturn)
args = ((ReturnAsArg) beforeReturn).getArgs();
}
Object returnObj = method.invoke(target, args);
String methodName = method == null ? null : method.getName();
for (AopHandler handler : handlers)
handler.after(target, method, methodName, args, returnObj);
return returnObj;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy