JAVA 框架-Spring-AOP面向切面

AOP(Aspect Orient Programming),我们一般称为面向方面(切面)编程,作为面向对象的一种补充,用于处理系统中分布于各个模块的横切关注点,比如事务管理、日志、缓存等等。AOP实现的关键在于AOP框架自动创建的AOP代理,AOP代理主要分为静态代理和动态代理,静态代理的代表为AspectJ;而动态代理则以Spring AOP为代表。

AOP配置示例:

需要的包:aspectjweaver-1.8.4.jar

数据访问层:

package com.hanqi.dao;public class AppuserDao {public int deleteUser(int ids) {System.out.println(ids +"被删除");yichang();//抛出一个异常return 1;}public void yichang() {throw new RuntimeException("出现错误!");}
}

 切面代理层:

package com.hanqi.util;public class LogginProxy {public void beforeMethod() {System.out.println("方法之前被调用!");}public void afterMethod() {System.out.println("方法之后被调用!");}public void returnMethod() {System.out.println("返回结果时被调用!");}public void throwMethod() {System.out.println("抛出异常时被调用!");}/*public void aroundMethod() {System.out.println("方法被调用");}*/
}

 spring.xml配置AOP

?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"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"><bean id="logginProxy" class="com.hanqi.util.LogginProxy"></bean><bean id="appuserdao" class="com.hanqi.dao.AppuserDao"></bean><aop:config><!-- 配置切点 --><aop:pointcutexpression="execution(* com.hanqi.dao.*.*(..))" id="aoppointcut" /><!--execution:执行,这句意为在执行com.hanqi.dao下的所有类时都会执行切面类--><!-- 指明切面类 --><aop:aspect ref="logginProxy"><aop:before method="beforeMethod"  pointcut-ref="aoppointcut"/><aop:after method="afterMethod" pointcut-ref="aoppointcut"/><aop:after-returning method="returnMethod" pointcut-ref="aoppointcut"/><aop:after-throwing method="throwMethod" pointcut-ref="aoppointcut"/>	</aop:aspect></aop:config>
</beans>

 JUnit Test测试:

package com.hanqi.util;import static org.junit.jupiter.api.Assertions.*;import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;import com.hanqi.dao.AppuserDao;class JUnittest {private ClassPathXmlApplicationContext c;private AppuserDao appuserdao;@BeforeEachvoid setUp() throws Exception {c = new ClassPathXmlApplicationContext("spring.xml");appuserdao = c.getBean(AppuserDao.class);}@AfterEachvoid tearDown() throws Exception {c.close();}@Testvoid test() {appuserdao.deleteUser(55);}}

 打印结果:

使用注解配置AOP

spring.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"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"><context:component-scan base-package="com.hanqi"></context:component-scan><!--配置扫描器-->
</beans>

数据访问层:

package com.hanqi.dao;import org.springframework.stereotype.Repository;@Repository//加到spring容器中,id名默认为类名首字母小写
public class AppuserDao {public int deleteUser(int ids) {System.out.println(ids +"被删除");yichang();return 1;}public void yichang() {throw new RuntimeException("出现错误!");}
}

 AppuserService类:

package com.hanqi.service;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;import com.hanqi.dao.AppuserDao;
@Repository
public class AppuserService {@Autowired//从spring容器中将该类自动放到当前类中的成员变量中,默认的装配类型时byType//@Qualifier("dao")该注解可将bean中id="dao"的类装配到该成员变量中,用于区分当类型相同时;private AppuserDao appuserDao;public int deleteUser(int ids) {return appuserDao.deleteUser(ids);}
}

 代理类:

package com.hanqi.util;import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Repository;@Repository//加到spring容器中,id名为类名首字母小写
@Aspect//声明当前类为切面类
@EnableAspectJAutoProxy//自动代理
public class LogginProxy {@Before("execution(* com.hanqi.dao.*.*(..))")//声明切点public void beforeMethod() {System.out.println("方法之前被调用!");}@After("execution(* com.hanqi.dao.*.*(..))")public void afterMethod() {System.out.println("方法之后被调用!");}@AfterReturning("execution(* com.hanqi.dao.*.*(..))")public void returnMethod() {System.out.println("返回结果时被调用!");}@AfterThrowing("execution(* com.hanqi.dao.*.*(..))")public void throwMethod() {System.out.println("抛出异常时被调用!");}/*public void aroundMethod() {System.out.println("方法被调用");}*/
}

 测试类:

package com.hanqi.util;import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;import com.hanqi.dao.AppuserDao;
import com.hanqi.service.AppuserService;class JUnittest {private ClassPathXmlApplicationContext c;private AppuserDao appuserdao;private AppuserService appuserService;@BeforeEachvoid setUp() throws Exception {c = new ClassPathXmlApplicationContext("spring.xml");//appuserdao = c.getBean(AppuserDao.class);appuserService = c.getBean(AppuserService.class);}@AfterEachvoid tearDown() throws Exception {c.close();}@Testvoid test() {//appuserdao.deleteUser(55);appuserService.deleteUser(66);}}

 

转载于:https://www.cnblogs.com/wyc1991/p/9245908.html

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

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

相关文章

互相关和卷积的关系

转载于:https://www.cnblogs.com/seisjun/p/10134021.html

Thymeleaf3语法详解

Thymeleaf是Spring boot推荐使用的模版引擎&#xff0c;除此之外常见的还有Freemarker和Jsp。Jsp应该是我们最早接触的模版引擎。而Freemarker工作中也很常见&#xff08;Freemarker教程&#xff09;。今天我们从三个方面学习Thymeleaf的语法&#xff1a;有常见的TH属性&#x…

【mysql】约束、外键约束、多对多关系

1、约束 DROP TABLE IF EXISTS emp;-- 员工表 CREATE TABLE emp (id INT PRIMARY KEY auto_increment, -- 员工id,主键且自增长ename VARCHAR(50) NOT NULL UNIQUE, -- 员工姓名,非空并且唯一joindate DATE NOT NULL, -- 入职日期,非空salary DOUBLE(7, 2) NULL, -- 工资,非空…

SSM+Netty项目结合思路

最近正忙于搬家&#xff0c;面试&#xff0c;整理团队开发计划等工作&#xff0c;所以没有什么时间登陆个人公众号&#xff0c;今天上线看到有粉丝想了解下Netty结合通用SSM框架的案例&#xff0c;由于公众号时间限制&#xff0c;我不能和此粉丝单独沟通&#xff0c;再此写一篇…

[6]Windows内核情景分析 --APC

APC&#xff1a;异步过程调用。这是一种常见的技术。前面进程启动的初始过程就是&#xff1a;主线程在内核构造好运行环境后&#xff0c;从KiThreadStartup开始运行&#xff0c;然后调用PspUserThreadStartup&#xff0c;在该线程的apc队列中插入一个APC&#xff1a;LdrInitial…

THYMELEAF 如何用TH:IF做条件判断

TestController 增加一个布尔值数据&#xff0c;并且放在model中便于视图上获取 package com.how2java.springboot.web; import java.util.ArrayList; import java.util.Date; import java.util.List;import org.springframework.stereotype.Controller; import org.springfr…

【mysql】多表查询、左外连接、内连接、练习题

多表查询 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FBdzXkoQ-1659581225088)(C:\Users\L00589~1\AppData\Local\Temp\1659337934641.png)] 左外连接&右外连接 -- 查询emp表所有数据和对应的部门信息 select * from emp left join dept o…

noi2018

day0 笔试没啥问题&#xff0c;基本都是100 day1 时间有点紧&#xff0c;念了2h题目&#xff0c;能写80848&#xff0c;第一题不会可持久化所以只能暴力。第二题感觉没第三个好做。第三题sa乱搞&#xff0c;随机串只hash长度小于20的。 最后几分钟才改过了所有小样例&#xff0…

Python自建collections模块

本篇将学习python的另一个内建模块collections,更多内容请参考:Python学习指南 collections是Python内建的一个集合模块&#xff0c;提供了许多有用的集合类。 namedtuple 我们知道tuple可以表示不变集合&#xff0c;例如&#xff0c;一个点的二维左边就可以表示成&#xff1a;…

Thymeleaf th:include、th:replace使用

最近做到页面数据展示分页的功能&#xff0c;由于每个模块都需要分页&#xff0c;所以每个页面都需要将分页的页码选择内容重复的写N遍&#xff0c;如下所示&#xff1a; 重复的代码带来的就是CtrlC&#xff0c;CtrlV ,于是了解了一下thymeleaf的fragment加载语法以及th:includ…

(OS X) OpenCV架构x86_64的未定义符号:错误(OpenCV Undefined symbols for architecture x86_64: error)...

原地址&#xff1a;http://www.it1352.com/474798.html 错误提示如下&#xff1a; Undefined symbols for architecture x86_64:"cv::_InputArray::_InputArray(cv::Mat const&)", referenced from:_main in test-41a30e.o"cv::namedWindow(std::__1::basic…

【算法】大根堆

const swap (arr, i, j) > {const tmp arr[i];arr[i] arr[j];arr[j] tmp; } const heapInsert (arr , i) > { // 插入大根堆的插入算法while(arr[i] > arr[Math.floor((i - 1) / 2]) {swap(arr, i, Math.floor((i - 1) / 2);i Math.floor((i - 1) / 2; } } cons…

[CF1082E] Increasing Frequency

Description 给定一个长度为 \(n\) 的数列 \(a\) &#xff0c;你可以任意选择一个区间 \([l,r]\) &#xff0c;并给区间每个数加上一个整数 \(k\) &#xff0c;求这样一次操作之后数列中最多有多少个数等于 \(c\)。 \(n,c,a_i\leq 10^5\) Solution 假设当前选择区间的右端点为 …

Thymeleaf select 使用 和多select 级联选择

1.使用select 并且回绑数据; 页面&#xff1a; 状态&#xff1a; <select name"status" th:field"*{status}" id"idstatus" class"input-select" th:value"*{status}"> <option value"">--请选择-…

Switch语句的参数是什么类型的?

在Java5以前&#xff0c;switch(expr)中&#xff0c;exper只能是byte&#xff0c;short&#xff0c;char&#xff0c;int类型。 从Java5开始&#xff0c;java中引入了枚举类型&#xff0c;即enum类型。 从Java7开始&#xff0c;exper还可以是String类型。 switch关键字对于多数…

【LOJ】#2184. 「SDOI2015」星际战争

题解 直接二分然后建图跑网络流看看是否合法即可 就是源点向每个激光武器连一条二分到的时间激光武器每秒攻击值的边 每个激光武器向能攻击的装甲连一条边 每个装甲向汇点连一条装甲值的边 代码 #include <bits/stdc.h> #define fi first #define se second #define pii …

表达式符号

Thymeleaf对于变量的操作主要有$*#三种方式&#xff1a; 变量表达式&#xff1a; ${…}&#xff0c;是获取容器上下文变量的值.选择变量表达式&#xff1a; *{…}&#xff0c;获取指定的对象中的变量值。如果是单独的对象&#xff0c;则等价于${}。消息表达式&#xff1a; #{……

Java学习的快速入门:10行代码学JQuery

生活在快速发展时代的我们&#xff0c;如果不提速可能稍不留神就被时代淘汰了。快节奏的时代成就了快餐&#xff0c;亦成就了速成教育。尤其是身处互联网行业的我们&#xff0c;更新换代的速度更是迅速&#xff0c;快速掌握一门技术已经成为潮流趋势。怎样才能快速入门学习java…

项目管理

项目先后衔接的各个阶段的全体被称为项目管理流程。项目管理流程对于一个项目能否高效的执行起到事半功倍的效果。接下来我会利用36张的ppt&#xff08;当然了这里我只用部分图片展示要不然就太多图片了&#xff09;&#xff0c;介绍项目管理的整体流程。 1.项目管理的五大过程…

docker——三剑客之Docker Machine

Docker Machine是Docker官方三剑客项目之一&#xff0c;负责使用Docker的第一步&#xff0c;在多种平台上快速安装Docker环境。它支持多种平台&#xff0c;让用户在很短时间内搭建一套Docker主机集群。Machine项目是Docker官方的开源项目&#xff0c;负责实现对Docker主机本身进…