一个简易的SpringAOP实例

1、引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>SpringAop_demo</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><!-- Spring Core --><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>5.3.9</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.3.9</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>5.3.9</version></dependency><!-- Spring AOP --><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>5.3.9</version></dependency><!-- AspectJ Weaver --><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.7</version></dependency><!-- AspectJ RT --><dependency><groupId>org.aspectj</groupId><artifactId>aspectjrt</artifactId><version>1.9.7</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.3.22</version></dependency></dependencies></project>

2、xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttps://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsd"><aop:aspectj-autoproxy /><!--目标类--><bean id="calculator" class="BasicCalculator" /><!--切面--><bean id="loggingAspect" class="LoggingAspect" /><aop:config><!--配置切面--><aop:aspect ref="loggingAspect"><!--配置切入点--><aop:pointcut id="pointMethod" expression="execution(* BasicCalculator.*(..))"/><aop:after-returning method="finallyAdd" pointcut-ref="pointMethod" returning="joinPoint"/></aop:aspect></aop:config>
</beans>

3、被代理对象接口与被代理对象

public interface Calculator {int add(int a, int b);
}
import org.springframework.aop.aspectj.AspectJExpressionPointcut;public class BasicCalculator implements Calculator {@Overridepublic int add(int a, int b) {int c = 0;try {System.out.println("add method into method add...");c = a + b;System.out.println("add method will return....");return c;}catch (Exception e){System.out.println("add method is error....");e.printStackTrace();}finally {System.out.println("add method is finally....");}return c;}
}

4、主函数

import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main {public static void main(String[] args) {ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");Calculator calculator = context.getBean(Calculator.class);int result = calculator.add(5, 3);System.out.println("Result: " + result);}}

还有一种可以写法,直接运行即可

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.transaction.annotation.Transactional;import java.lang.reflect.Method;public class tesAspect {public static void main(String[] args) throws NoSuchMethodException {//切点AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();pointcut.setExpression("execution(* *(..))");System.out.println(pointcut.matches(Target.class.getMethod("foo"), Target.class));//通知MethodInterceptor advice = new MethodInterceptor() {@Overridepublic Object invoke(MethodInvocation methodInvocation) throws Throwable {System.out.println("before..");Object result = methodInvocation.proceed();System.out.println("after..");return result;}};//切面DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor(pointcut, advice);Target target1 = new Target();ProxyFactory proxyFactory = new ProxyFactory();proxyFactory.setTarget(target1);proxyFactory.addAdvisor(advisor);A1 a1 = (A1) proxyFactory.getProxy();System.out.println(a1.getClass());a1.foo();a1.bar();//检查类与方法是否有Transaction注解StaticMethodMatcherPointcut pointcut1 = new StaticMethodMatcherPointcut() {@Overridepublic boolean matches(Method method, Class<?> aClass) {//检查方法上是否加了Transaction注解MergedAnnotations annotation = MergedAnnotations.from(method);if(annotation.isPresent(Transactional.class)){return true;}//检查方法上是否加了注解annotation = MergedAnnotations.from(aClass, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY);if(annotation.isPresent(Transactional.class)){return true;}return false;}};System.out.println(pointcut1.matches(Target.class.getMethod("foo"), Target.class));}@Transactionalinterface A1{void foo();void bar();}static class Target implements A1{@Overridepublic void foo() {System.out.println("foo");}@Overridepublic void bar() {System.out.println("bar");}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/595800.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【电商项目实战】沙箱支付模拟支付功能

&#x1f389;&#x1f389;欢迎来到我的CSDN主页&#xff01;&#x1f389;&#x1f389; &#x1f3c5;我是Java方文山&#xff0c;一个在CSDN分享笔记的博主。&#x1f4da;&#x1f4da; &#x1f31f;推荐给大家我的专栏《电商项目实战》。&#x1f3af;&#x1f3af; &am…

芯片SIC8833可开发打气泵方案

无线车载打气泵方案由一块PCBA板集成其所需的功能&#xff0c;其充气原理是发动机通过两根三角带驱动气泵曲轴&#xff0c;进而驱动活塞进行打气&#xff0c;打出的气体通过导气管导入储气筒。另一方面储气筒又通过一根导气管将储气筒内的气体导入固定在气泵上的调压阀内&#…

orangepi 3b安装 miniconda,后安装 opencv-python

参考 https://docs.conda.io/projects/miniconda/en/latest/ 下载miniconda wget https://repo.anaconda.com/miniconda/Miniconda3-py311_23.11.0-2-Linux-aarch64.sh -O ~/miniconda3/miniconda.sh mkdir -p ~/miniconda3 #wget https://repo.anaconda.com/miniconda/Mi…

ClickHouse基础知识(四):ClickHouse 引擎详解

1. 表引擎的使用 表引擎是 ClickHouse 的一大特色。可以说&#xff0c; 表引擎决定了如何存储表的数据。包括&#xff1a; ➢ 数据的存储方式和位置&#xff0c;写到哪里以及从哪里读取数据。 默认存放在/var/lib/clickhouse/data ➢ 支持哪些查询以及如何支持。 ➢ 并发数…

6.vue学习笔记(style绑定+监听器+表单的输入绑定)

文章目录 1.style绑定2.监听器3.表单的输入绑定3.1.复选框3.2.修饰符3.2.1 .lazy 1.style绑定 数据绑定的一个常见需求场景是操纵元素的 CSS style列表&#xff0c;因为style是attribute&#xff0c;我们可以和其他attribute一样使用v-bind将它们和动态字符串绑定。 但是&…

vue-cli创建项目时由esLint校验导致报错或警告的问题及解决

vue-cli创建项目时由esLint校验导致报错或警告的问题及解决 一、万能办法 一、万能办法 //就是在报错的JS文件中第一行写上 /* eslint-disable */链接: https://www.yii666.com/blog/288808.html 其它的方法我遇见了再补充

easycode 插件配置文件

easycode是一个idea生成文件的插件&#xff0c;以下是我的一个项目中配置信息&#xff0c;需要的可以拿走&#xff0c;保存成json文件导入即可 {"author" : "XXX","version" : "1.2.8","userSecure" : "","…

快速搭建知识付费小程序,3分钟即可开启知识变现之旅

产品服务 线上线下课程传播 线上线下活动管理 项目撮合交易 找商机找合作 一对一线下交流 企业文化宣传 企业产品销售 更多服务 实时行业资讯 动态学习交流 分销代理推广 独立知识店铺 覆盖全行业 个人IP打造 独立小程序 私域运营解决方案 公域引流 营销转化 …

spark解决scala.matchError问题

在代码里处理match问题的时候报scala.matchError问题 处理方式很简单 我们在做match{case }的时候&#xff0c;有时候会忽略需要加一个总管所有未匹配上的情况&#xff0c;也就是缺少 case _ > … 这样的条件&#xff0c;加上就好了&#xff0c;基本用不到这一层&#xff0c…

深度学习基础知识神经网络

神经网络 1. 感知机 感知机&#xff08;Perceptron&#xff09;是 Frank Rosenblatt 在1957年提出的概念&#xff0c;其结构与MP模型类似&#xff0c;一般被视为最简单的人工神经网络&#xff0c;也作为二元线性分类器被广泛使用。通常情况下指单层的人工神经网络&#xff0c…

面试题:Docker命令大全及相关技术名词

Docker相关技术名词&#xff1a; 镜像&#xff08;Image&#xff09;&#xff1a;Docker将应用程序及其所需的依赖、函数库、环境、配置等文件打包在一起&#xff0c;称为镜像。 容器&#xff08;Container&#xff09;&#xff1a;镜像中的应用程序运行后形成的进程就是容器…

ModuleNotFoundError: No module named ‘numpy.testing.decorators‘

文章目录 报错信息报错原因解决方案 关注公众号&#xff1a;『AI学习星球』 算法学习、4对1辅导、论文辅导或核心期刊可以通过公众号或➕v&#xff1a;codebiubiubiu滴滴我 报错信息 ModuleNotFoundError: No module named numpy.testing.decorators 报错原因 新版本已经去…

【C++】知识点汇总(下)

C知识点复习下 一、面向对象编程&#xff1a;深入理解类与对象1.类的定义和访问2.this指针3.构造函数与析构函数4.重载和拷贝构造函数5.常成员和静态成员6.友元 二、运算符重载1. 规则2. 成员或友元重载2.1 例子&#xff1a;成员函数重载2.2 例子&#xff1a;友元函数重载 3. 类…

how2heap-2.23-03-fastbin_dup_consolidate

#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h>int main() {void* p1 malloc(0x10);strcpy(p1, "AAAAAAAA");void* p2 malloc(0x10);strcpy(p2, "BBBBBBBB");fprintf(stderr, "申请两个…

手机怎么边看视频边记笔记或备忘录?

在这个信息爆炸的时代&#xff0c;我们经常需要通过看培训视频、听网课来不断充实自己。但是&#xff0c;手机屏幕那么小&#xff0c;如何才能在做笔记的同时&#xff0c;又不错过视频的每一个细节呢&#xff1f; 以前&#xff0c;我总是为此头疼。一手拿着手机看视频&#xf…

【嵌入式】About USB Powering

https://www.embedded.com/usb-type-c-and-power-delivery-101-power-delivery-protocol/https://www.embedded.com/usb-type-c-and-power-delivery-101-power-delivery-protocol/ Type-C接口有多强&#xff1f;PD协议又是什么&#xff1f;-电子发烧友网由于Type-C接口自身的强…

网站报错:nginx 413 Request Entity Too Large

问题描述 我在上传一个图片文件的时候&#xff0c;收到 Nginx 报错&#xff1a; 413 Request Entity Too Large 问题原因 Nginx 默认上传文件大小是 1 MB&#xff0c;如果上传过大文件&#xff0c;会报上面的错误。 解决方法 需要修改nginx的配置文件。以下是如何修改的步…

c++牛客总结

一、c/c语言基础 1、基础 1、指针和引用的区别 指针是一个新的变量&#xff0c;指向另一个变量的地址&#xff0c;我们可以通过这个地址来修改该另一个变量&#xff1b; 引用是一个别名&#xff0c;对引用的操作就是对变量本身进行操作&#xff1b;指针可以有多级 引用只有一…

【QT】return 和 break 是 C++ 中两个不同的关键字,它们在程序中有不同的用途。

return 和 break &#xff1a; return&#xff1a; 用于从函数中返回值&#xff0c;结束函数的执行&#xff0c;并将控制返回到调用函数的地方。在函数体中&#xff0c;当执行到 return 语句时&#xff0c;函数将立即退出&#xff0c;不再执行后续的语句。可以带有一个值&#…

2024年软考什么时候报名?一年考几次?

2024年上半年报名时间预计在3月中上旬开始&#xff0c;考试时间预计为5月25日。 报考条件及报名流程 报考条件&#xff1a; 1.遵守中华人民共和国宪法和各项法律&#xff0c;恪守职业道德&#xff0c;具有一定计算机技术应用能力的人员&#xff0c;均可根据本人情况报名参加…