AOP初識及實踐
AOP是什么?
AOP(Aspect Oriented Programming),即為面向切面編程,其作為一種新的編程思想,主要是將多數代碼中共用的部分抽象出來,采用動態代理、靜態代理等方式,自動添加到對應代碼的首部或尾部,從而簡化業務代碼重復邏輯,提升開發效率,

AOP常見概念
- 增強/通知(advice),在特定連接點需要執行的動作,Spring下主要包括五種通知型別:
- 前置通知(Before)
- 后置通知(After)
- 回傳通知(After-returning)
- 例外通知(After-throwing)
- 環繞通知(Around)
- 切點(pointcut),指在特定連接點應該呼叫的時機,
- 連接點(Joint Point),指的是可以應用通知進行增強的方法,
- 切面(Aspect),切入點和通知的結合
- 織入(weaving),通過代理對目標物件方法進行增強的程序,

AOP原理
AOP實作的原理,主要基于代理模式,其又主要分為兩種:1、靜態代理;2、動態代理,
靜態代理
靜態代理來說相對比較簡單,主要邏輯如下所示:

主要關注幾個點:
1、被代理類與代理類需要共同實作一個代理介面的方法,
2、被代理類需要通過getter、setter方法注入到代理類中,
3、外部呼叫代理類的方法,從而實作增強邏輯,
具體代碼實作如下:
@Data
@Slf4j
public class NormalAction implements MyFunction { // 被代理類
@Override
public void display() {
LOGGER.info("我是被代理的用戶,我很苦逼!");
}
}
@Slf4j
@Data
public class StaticProxyAction implements MyFunction { // 代理類
NormalAction normalAction;//被注入的代理類,由getter、setter方法注入
@Override
public void display() {
LOGGER.info("我是代理人>>>>>>>>");
LOGGER.info("開始代理>>>>>>>>");
normalAction.display();
LOGGER.info("結束代理>>>>>>>>");
}
}
@ApiModel(value = "需實作的代理介面")
public interface MyFunction {
public void display();
}
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
//Spring首先注入被代理人到容器中
NormalAction normalAction = new NormalAction();
//然后Spring將被代理人注入到代理類中
StaticProxyAction staticProxyAction = new StaticProxyAction();
staticProxyAction.setNormalAction(normalAction);
//呼叫MyFunction方法的時候,即可實作增強!
staticProxyAction.display();
}
}
輸出結果:
可以看到,整個程序中,被代理類的方法并沒有進行修改,但是前后邏輯確實發生了變化,這就是AOP所謂的無侵入性,
動態代理
JDK動態代理
代碼實踐:
采用JDK的動態代理,需要自定義一個對應的Handler類,其繼承了InvocationHandler類,并需要對相應的invoke方法進行多載,通過傳入的方式對當前的invokeResult進行呼叫,
@Data
@Slf4j
public class DynamicProxyHandler implements InvocationHandler {
//被代理的物件
private Object object;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
LOGGER.info("你被增強了!快上!");
Object invokeResult = method.invoke(object, args);
LOGGER.info("增強結束!");
return invokeResult;
}
}
主函式中,通過Proxy物件新建對應的類加載器,并呼叫對應的方法實作,
public static void main(String[] args) {
NormalAction normalAction = new NormalAction();
DynamicProxyHandler dynamicProxyHandler = new DynamicProxyHandler();
dynamicProxyHandler.setObject(normalAction);
//獲取對應的代理介面
MyFunction proxyInstance = (MyFunction) Proxy.newProxyInstance(NormalAction.class.getClassLoader(), // 類加載器
NormalAction.class.getInterfaces(), // 需要增強的介面
dynamicProxyHandler);// 實際代理類
//呼叫對應的介面資訊
proxyInstance.display();
}

底層原理:
@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h) throws IllegalArgumentException
{
Objects.requireNonNull(h);
// 拷貝出介面陣列
final Class<?>[] intfs = interfaces.clone();
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
//依據類加載器及介面,查找并創建對應的代理類
//將相應的位元組碼檔案,注入到被代理類中,同時,呼叫defineClass0來決議位元組碼,最終生成了Proxy的Class物件,
Class<?> cl = getProxyClass0(loader, intfs);
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
//獲取到InvocationHandler類的構建器
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if (!Modifier.isPublic(cl.getModifiers())) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
cons.setAccessible(true);
return null;
}
});
}
// 根據構造器創建對應的新實體
return cons.newInstance(new Object[]{h});
} catch (IllegalAccessException|InstantiationException e) {
throw new InternalError(e.toString(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString(), t);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString(), e);
}
}
CGLIB動態代理
代碼實踐:
@Slf4j
public class CglibProxy implements MethodInterceptor { // 繼承相應的方法攔截器
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
LOGGER.info("你被增強了!");
Object object = methodProxy.invokeSuper(o, objects);
LOGGER.info("增強結束!");
return object;
}
}
public class ProxyApplication {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer(); // 創建增強器
enhancer.setSuperclass(NormalAction.class); // 設定被增強的類
enhancer.setCallback(new CglibProxy()); // 設定代理類
NormalAction proxyInstance = (NormalAction) enhancer.create(); // 創建代理實體
proxyInstance.display(); // 呼叫被代理方法
}
}

底層原理:
private Object createHelper() {
// 預先的校驗邏輯
preValidate();
// 根據對應的superclassName 生成對應的類
Object key = KEY_FACTORY.newInstance((superclass != null) ? superclass.getName() : null,
ReflectUtils.getNames(interfaces),
filter == ALL_ZERO ? null : new WeakCacheKey<CallbackFilter>(filter),
callbackTypes,
useFactory,
interceptDuringConstruction,
serialVersionUID);
this.currentKey = key;
// 根據這個key再生成相應的代理類物件
Object result = super.create(key);
return result;
}
protected Object create(Object key) { // 根據被代理類的加載器加載對應的類書籍
try {
// 獲取類加載器
ClassLoader loader = this.getClassLoader();
// 獲取快取
Map<ClassLoader, AbstractClassGenerator.ClassLoaderData> cache = CACHE;
AbstractClassGenerator.ClassLoaderData data = (AbstractClassGenerator.ClassLoaderData)cache.get(loader);
//經典的雙重校驗鎖,保證執行緒安全
if (data == null) {
Class var5 = AbstractClassGenerator.class;
synchronized(AbstractClassGenerator.class) {
cache = CACHE;
data = (AbstractClassGenerator.ClassLoaderData)cache.get(loader);
if (data == null) {
// 創建弱參考的哈希表,并保存到快取中
Map<ClassLoader, AbstractClassGenerator.ClassLoaderData> newCache = new WeakHashMap(cache);
data = new AbstractClassGenerator.ClassLoaderData(loader);
newCache.put(loader, data);
CACHE = newCache;
}
}
}
//保存對應的key值
this.key = key;
Object obj = data.get(this, this.getUseCache()); //=====>深入進入
return obj instanceof Class ? this.firstInstance((Class)obj) : this.nextInstance(obj);
} catch (Error | RuntimeException var9) {
throw var9;
} catch (Exception var10) {
throw new CodeGenerationException(var10);
}
}
// 獲取對應的類資料資訊
public Object get(AbstractClassGenerator gen, boolean useCache) {
if (!useCache) {
// 不使用快取的話,直接利用資料生成新的抽象類
return gen.generate(this);
} else {
// 從快取中獲取
Object cachedValue = generatedClasses.get(gen);
return gen.unwrapCachedValue(cachedValue);
}
}
AOP最佳實踐
RPC日志組件
首先引入對應的包依賴:
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
定義切點有兩種方式:
1、采用execution運算式,指定對應的函式執行的時刻,
2、采用注解,在對應需要增強的地方進行織入,
這里我們采用方法二,首先定義一個自己的注解,需要注意的是,注解的作用只是給你的代碼打下一個標記,需要對應采用反射或者特殊的處理類對標記的代碼進行處理,
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation {
String SERVER_NAME() default "";
String action() default "";
}
緊接著,定義我們的切面類,對相應的切面方法進行增強,
@Aspect
@Component
@Slf4j
public class MyAspect {
//采用execution運算式的方式定義切點
@Pointcut("execution(* com.example.demo.controller..*.*(..)) ")
private void PointCutofAnno(){}
//或是直接 采用注解的方法定義,需要注意的是,如果需要使用注解內的值,需要保持變數名稱都是“myAnnotation”
@Around(value = "@annotation(myAnnotation)")
public <T> T test(ProceedingJoinPoint point, MyAnnotation myAnnotation) throws Throwable {
// 撰寫相應的增強代碼
ResultDTO<T> res;
String serverName = myAnnotation.SERVER_NAME();
String action = myAnnotation.action();
LOGGER.info("AOP執行前,{}", JSONObject.toJSONString(point.getArgs()));
try{
res = (ResultDTO<T>) point.proceed();
}catch (Exception e){
throw new NrsBusinessException(500, String.format("請求%s%s時失敗,錯誤資訊為:%s",serverName,action,e.getMessage()),e);
}
if (res == null) {
throw new NrsBusinessException(500, String.format("請求%s%s時回傳值為空", serverName,action));
}
if (res.isSuccess()) {
return res.getData();
} else {
throw new NrsBusinessException(500,String.format("請求%s%s時, %s例外,code為:%d,錯誤資訊為:%s",serverName, action, serverName,res.getCode(), res.getMessage()));
}
}
}
最后,在我們呼叫下游的函式處添加上對應的注解,從而實作對相應RPC例外的處理,
@Component
public class MyRpc {
@MyAnnotation(SERVER_NAME = "下游系統",action = "呼叫下游系統時")
public ResultDTO<Boolean> testFunction(){
ResultDTO<Boolean> resultDTO = new ResultDTO<>();
resultDTO.success(true);
return resultDTO;
}
}
@Service("testService")
public class TestService {
@Resource
MyRpc myRpc;
public Boolean test(){
return myRpc.testFunction().getData();
}
}
@RestController
@RequestMapping(value = "")
public class TestController {
@Resource
TestService testService;
@GetMapping("/test")
public ResultDTO<Boolean> myTest() {
return new ResultDTO<>().success(testService.test());
}
}
PS:ResultDTO為自定義的結果類,可以根據自己的業務自定義,一般包括回傳的錯誤碼、回傳的資料內容以及呼叫的錯誤資訊,
參考文獻
AOP實戰:一個面向切面的實戰專案,方法級別的簡單監控
java-AOP徹底決議
JAVA動態代理
cglib動態代理機制
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/395438.html
標籤:其他
上一篇:動態資源(servlet)
下一篇:SpringBoot檔案上傳
