博客
关于我
spring5.1.x源码解析之五(AOP)
阅读量:634 次
发布时间:2019-03-13

本文共 4930 字,大约阅读时间需要 16 分钟。

Spring AOP 详解

Spring AOP(Spring 一款 aspect-oriented programming 框架)通过动态代理和切面编程,帮助开发者非侵入性地扩展现有系统。以下将从 bean 的编写、AOP 的配置、以及动态代理机制的实现等方面,详细阐述 Spring AOP 的工作原理。

Bean 的编写

在 Spring AOP 中,bean 是应用程序中配置的核心组件。开发者需要编写 bean 类,以便框架能够管理其生命周期。通常,开发者会使用 @Autowired@Resource 等注解来注入依赖项。以下是一个典型的 bean 类:

@AllArgsConstructor@Data@NoArgsConstructorpublic class MyBeanTest implements InitializingBean, DisposableBean {    private String testStr = "testStr";    public void test() {        System.out.println(testStr);    }    @Override    public void afterPropertiesSet() throws Exception {        System.out.println("InitializingBean");    }    @Override    public void destroy() throws Exception {        System.out.println("死了");    }}

AOP 配置

要实现 AOP,开发者需要定义切点和增强逻辑。以下是一个示例:

package org.example.aop;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.AfterThrowing;import org.aspectj.lang.annotation.AfterReturning;import org.aspectj.lang.annotation.Around;@Aspectpublic class AopTest {    @Pointcut("execution (* *.test(..))")    public void test() {}    @Before("test()")    public void begin() {        System.out.println("开启事务");    }    @After("test()")    public void commit() {        System.out.println("提交事务");    }    @AfterThrowing("test()")    public void afterThrowing() {        System.out.println("afterThrowing");    }    @AfterReturning("test()")    public void afterReturning() {        System.out.println("AfterReturning");    }    @Around("test()")    public void around(ProceedingJoinPoint pj) throws Throwable {        System.out.println("环绕前");        pj.proceed();        System.out.println("环绕后");    }}

配置文件

applicationContext.xml 中,启用 AOP 的配置如下:

动态代理机制

Spring AOP 通常使用 JDK 动态代理或 CGLIB 过滤代理来实现动态增强。核心逻辑在 AnnotationAwareAspectJAutoProxyCreator 类中。

JDK 动态代理

JDK 动态代理基于 Java 给予式代理(Proxy),适用于非接口目标类。原逻辑代码如下:

public class DynamicAdvisedInterceptor implements MethodInterceptor {    private final AdvisedSupport advised;    public DynamicAdvisedInterceptor(AdvisedSupport advised) {        this.advised = advised;    }    public Object intercept(Object proxy, Method method, Object[] args,                           MethodProxy methodProxy) throws Throwable {        Object oldProxy = null;        boolean setProxyContext = false;        try {            if (advised.exposeProxy) {                oldProxy = AopContext.setCurrentProxy(proxy);                setProxyContext = true;            }            Object target = advised.getTargetSource().confirmTarget();            Class
targetClass = (target != null) ? target.getClass() : null; List chain = advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass); if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) { Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args); Object ret_val = methodProxy.invoke(target, argsToUse); return ret_val; } else { MethodInvocation invocation = new ReflectiveMethodInvocation(target, method, args, targetClass, chain); return invocation.proceed(); } } catch (Throwable e) { throw AopInvocationExceptionUtil.containsErrorCode(AopInvocationException.E 계속...
CGLIB 森林代理

CGLIB代理基于 C transcripts of Java bytecode,适用于目标类为 final 或存在其他问题时。以下是 CGLIB 创建代理的过程:

public class ObjenesisCglibAopProxy implements AopProxy {    private final AdvisedSupport advised;    public ObjenesisCglibAopProxy(AdvisedSupport advised) {        this.advised = advised;    }    public Object getProxy(ClassLoader classLoader) {        try {            Enhancer enhancer = createEnhancer();            enhancer.setClassLoader(classLoader);            enhancer.setSuperclass(advised.getTargetClass());            enhancer.setInterfaces(AopProxyUtils provádíSupport(targetClass));            enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);            enhancer.setStrategy(new ClassLoaderAwareUndeclaredThrowableStrategy(classLoader));            Callback[] callbacks = getCallbacks(advised.getTargetClass());            Class
[] types = new Class[callbacks.length]; for (int x = 0; x < types.length; x++) { types[x] = callbacks[x].getClass(); } enhancer.setCallbackFilter(new ProxyCallbackFilter(advised.getConfigurable(), fixedInterceptorMap, fixedInterceptorOffset)); enhancer.setCallbackTypes(types); enhancer.create-aged proxy class; enhancer.create-aged proxy instance; return proxy; } catch (CodeGenerationException | IllegalArgumentException e) { throw new AopConfigException("...", e); } }

总结

通过上述内容,可以看出 Spring AOP 的核心功能在于动态代理和切面编程。通过配置 aspectj-autoproxy,开发者可以轻松为 bean 类加入增强逻辑。动态代理则确保了 AOP 的实现与原有系统的无缝集成。

转载地址:http://qnwoz.baihongyu.com/

你可能感兴趣的文章
NLog 自定义字段 写入 oracle
查看>>
NLog类库使用探索——详解配置
查看>>
NLP 基于kashgari和BERT实现中文命名实体识别(NER)
查看>>
NLP 项目:维基百科文章爬虫和分类【01】 - 语料库阅读器
查看>>
NLP_什么是统计语言模型_条件概率的链式法则_n元统计语言模型_马尔科夫链_数据稀疏(出现了词库中没有的词)_统计语言模型的平滑策略---人工智能工作笔记0035
查看>>
NLP学习笔记:使用 Python 进行NLTK
查看>>
NLP的神经网络训练的新模式
查看>>
NLP采用Bert进行简单文本情感分类
查看>>
NLP问答系统:使用 Deepset SQUAD 和 SQuAD v2 度量评估
查看>>
NLP:使用 SciKit Learn 的文本矢量化方法
查看>>
Nmap扫描教程之Nmap基础知识
查看>>
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>