AOP的概念

image-20250127160224020

AOP思想的实现方案

image-20250127160708339

模拟AOP的基础代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class MockAopBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {

private ApplicationContext applicationContext;

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// 对 com.nju.service.impl 下的类进行增强
if (bean.getClass().getPackage().getName().equals("com.nju.service.impl")) {
// 动态代理
Object beanProxy = Proxy.newProxyInstance(
bean.getClass().getClassLoader(),
bean.getClass().getInterfaces(),
(Object proxy, Method method, Object[] args) -> {
// MyAdvice是用来增强的类
MyAdvice myAdvice = applicationContext.getBean(MyAdvice.class);
myAdvice.beforeAdvice();
Object result = method.invoke(bean, args);
myAdvice.afterAdvice();
return result;
}
);
return beanProxy;
}

return bean;
}

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
// 注入上下文
this.applicationContext = applicationContext;
}
}

AOP相关概念

image-20250127164924526