Spring AOP面向切面编程实现原理方法详解
作者:弥漫s 发布时间:2021-07-22 00:26:07
1. 什么是AOP
AOP (Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期 * 实现在不修改源代码的情况下,给程序动态统一添加功能的一种技术,可以理解成 * 。是Spring框架中的一个重要内容。利用 AOP 可以对业务逻辑的各个部分进行隔离,使业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高开发的效率
2. Spring AOP
①. AOP 在Spring中的作用
提供声明式事务;允许用户自定义切面
②. AOP 的基本概念
横切关注点:跨越应用程序多个模块的方法或功能。即与我们业务逻辑无关,但需要我们关注的部分就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 ....
Aspect(切面):横切关注点被模块化的特殊对象。通常是一个类,里面可以定义切入点和通知
Weaving(织入):把切面(aspect)连接到其它的应用程序类型或者对象上,并创建一个被通知(advised)的对象。 这些可以在编译时,类加载时和运行时完成。Spring和其它纯Java AOP框架一样,在运行时完成织入
Advice(通知):AOP在特定的切入点上执行的增强处理,是切面必须要完成的工作,也是类中的一个方法
Target(目标):被通知对象
AOP(代理):AOP框架创建的对象,代理就是目标对象的加强。Spring中的 AOP 代理可以是 JDK * ,也可以是 CGLIB 代理,前者基于接口,后者基于子类
JointPoint(连接点):程序执行过程中明确的点,一般是方法的调用
Pointcut(切入点):就是带有通知的连接点,与切入点匹配的执行点
③. 使用Spring实现Aop
前提
使用AOP织入,需要导入一个依赖包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
实现Aop的三种方式
方式一:通过 Spring API 实现【主要是springAPI接口实现】
首先编写业务接口和实现类
public interface UserService {
public void add();
public void delete();
public void update();
public void search();
}
public class UserServiceImpl implements UserService{
public void add() {
System.out.println("增加了一个用户");
}
public void delete() {
System.out.println("删除了一个用户");
}
public void update() {
System.out.println("更新了一个用户");
}
public void select() {
System.out.println("查询了一个用户");
}
}
接着编写增强类,这里写两个:前置增强Log和后置增强AfterLog
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class Log implements MethodBeforeAdvice {
//method: 要执行的目标对象的方法
//args: 参数
//target: 目标对象
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class AfterLog implements AfterReturningAdvice {
//returnValue;返回值
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"方法,返回结果为:"+returnValue);
}
}
最后在Spring的文件中注册( applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册bean-->
<bean id="userService" class="com.lf.service.UserServiceImpl"/>
<bean id="log" class="com.lf.log.Log"/>
<bean id="afterLog" class="com.lf.log.AfterLog"/>
<!--方式一:使用原生Spring API接口 -->
<!--配置aop:需要导入aop的约束-->
<aop:config>
<!--切入点:expression:表达式,execution(要执行的位置! * * * * *) -->
<aop:pointcut id="pointcut" expression="execution(* com.lf.service.UserServiceImpl.*(..))"/>
<!--执行环绕; advice-ref执行方法 . pointcut-ref切入点-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
进行测试:
import com.lf.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService1 = (UserService) context.getBean("userService");
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
运行结果:
com.lf.service.UserServiceImpl的add被执行了
增加了一个用户
执行了add方法,返回结果为:null
方式二:自定义类实现AOP【主要是切面定义】
目标业务类不变,还是方式一中的UserServiceImpl
写入一个切入类
public class DiyPointCut {
public void before(){
System.out.println("========方法执行前=========");
}
public void after(){
System.out.println("========方法执行后=========");
}
}
在Spring中配置(applicationContext.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/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册bean-->
<bean id="userService" class="com.lf.service.UserServiceImpl"/>
<bean id="log" class="com.lf.log.Log"/>
<bean id="afterLog" class="com.lf.log.AfterLog"/>
<!--方式二:自定义类-->
<bean id="diy" class="com.lf.diy.DiyPointCut"/>
<aop:config>
<!--自定义切面, ref 要引用的类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* com.lf.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
</beans>
在上面的 MyTest.java 中测试,得到结果:
========方法执行前=========
增加了一个用户
========方法执行后=========
方式三:使用注解实现【多用】
编写一个注解实现的增强类
package com.lf.diy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {
@Before("execution(* com.lf.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("=====方法执行前======");
}
@After("execution(* com.lf.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("=====方法执行后======");
}
//在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点;
@Around("execution(* com.lf.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
Signature signature = jp.getSignature();//获得签名
System.out.println("signature:"+signature);
Object proceed = jp.proceed(); //执行方法
System.out.println("环绕后");
System.out.println(proceed);
}
}
在Spring配置文件中,注册bean,并增加支持注解的配置
<?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/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册bean-->
<bean id="userService" class="com.lf.service.UserServiceImpl"/>
<bean id="log" class="com.lf.log.Log"/>
<bean id="afterLog" class="com.lf.log.AfterLog"/>
<!--方式三-->
<bean id="annotationPointCut" class="com.lf.diy.AnnotationPointCut"/>
<!--开启注解支持! JDK(默认 proxy-target-class="false") cglib(proxy-target-class="true")-->
<aop:aspectj-autoproxy/>
</beans>
在 MyTest.java 中测试
import com.lf.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
得到结果:
环绕前
signature:void com.lf.service.UserService.add()
=====方法执行前======
增加了一个用户
=====方法执行后======
环绕后
null
来源:https://www.cnblogs.com/lf-637/p/13401297.html


猜你喜欢
- Spingboot JPA CriteriaBuilder获取指定字段废话不说直接贴代码public class ActivityVO im
- import java.util.Arrays;/** * 栈的实现<br> * @author Skip&
- 本文实例为大家分享了使用PageHelper插件实现Service层分页的具体代码,供大家参考,具体内容如下使用场景:平时分页我们可以直接使
- 在实际的应用程序开发中,我们有时需要把 Activity 设置成全屏显示,一般情况下,可以通过两种方式来设置全屏显示效果:其一,通过在代码中
- 最近发现线上监控有个SQL调用量很大,但是方法的调用量不是很大,查看接口实现,发现接口是做了缓存操作的,使用Spring cache缓存注解
- 本文介绍了Spring Boot Admin监控服务上下线邮件通知,分享给大家,具体如下:微服务架构下,服务的数量少则几十,多则上百,对服务
- Android 是一款基于 Linux 内核,面向移动终端的操作系统。为适应其作为移动平台操作系统的特殊需要,谷歌对其做了特别的设计与优化,
- 之前的文章都是讲解springmvc+spring+mybatis 的整合,而很少有springmvc+spring+hibernate 因
- 本文实例总结了C#中WinForm程序退出方法技巧。分享给大家供大家参考。具体分析如下:在c#中退出WinForm程序包括有很多方法,如:t
- 一、介绍Properties文件在Java中主要为配置文件,文件类型为:.properties,格式为文本文件,内容格式为"键=值
- springboot项目启动慢的问题排查springboot项目,随着时间的推移,启动耗时逐步增加,从几分钟慢慢的达到30多分钟,有点恐怖!
- mybatis的SqlSession一定要关闭今天在使用mybatis查询数据时,出现了一个很奇怪的问题。同一条sql语句,查询时快时慢,并
- 面向对象思想之封装或许大家都听说过java是纯面向对象语言,面向对象思想也就是我们常说的OOP,我们听说最多的思想就是继承,封装,多态,今天
- 新配置一个spring的MVC项目,发现对Get请求的中文参数出现了乱码:查看了SpingMVC中关于编码的配置(在web.xml中),如下
- 1.元组(Tuple)元组(Tuple)在4.0 的时候就有了,但元组也有些缺点,如: 1)Tuple 会影响代码的
- 最可怕的不是犯错而是一直都没发现错误,直到现在我才知道自己对类变量的理解有问题。大概可能也许是因为不常用类变量的原因吧,一直没有发现这个问题
- 安卓系统本身可以很简便的实现分享功能,因为我们只需向startActivity传递一个ACTION_SEND的Intent,系统就为我们弹出
- 最近项目中遇到一个问题,在用户没填数据的时候,我们需要接收从前端传过来的对象为null,但是前端说他们一个一个判断特别麻烦,只能传个空对象过
- 本文实例讲述了C#采用递归实现阶乘的方法,供大家参考之用。通常来说,如果想实现一个阶乘,比如6 * 5 * 4 * 3 * 2 * 1,首先
- 一、代码结构:二、数据实体类:using System;using System.Collections.Generic;using Sys