大家好,很高兴再次与大家见面,我是你们的朋友全栈君。
Spring的AOP操作是通过AspectJ来实现的,AspectJ是一个基于Java语言的AOP框架,Spring2.0以后新增了对AspectJ切点表达式的支持。接下来我们将详细介绍基于AspectJ的AOP操作。
准备工作
新建一个Java项目,导入jar包:
![【spring】AOP实践[通俗易懂]](https://img.php.cn/upload/article/001/503/042/175306875728442.jpg)
引入约束:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"></beans>
新建增强类(Book)和被增强的类(MyBook)
public class Book {
public void add(){
System.out.println("add.......");
}
}
<p>public class MyBook {
public void before(){
System.out.println("前置增强.....");
}
public void after(){
System.out.println("后置增强.....");
}
//环绕增强
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
//方法之前
System.out.println("方法之前.....");
//执行被增强的方法
proceedingJoinPoint.proceed();
//方法之后
System.out.println("方法之后.....");
}
}一. 通过配置文件实现AOP操作
<bean class="cn.itcast.aop.Book" id="book"></bean> <bean class="cn.itcast.aop.MyBook" id="myBook"></bean> <config> <pointcut expression="execution(<em> cn.itcast.aop.Book.</em>(..))" id="pointcut1"></pointcut> <aspect ref="myBook"> <before method="before" pointcut-ref="pointcut1"></before> <after-returning method="after" pointcut-ref="pointcut1"></after-returning> <around method="around" pointcut-ref="pointcut1"></around> </aspect> </config>
调用book对象的add方法,输出结果如下:
![【spring】AOP实践[通俗易懂]](https://img.php.cn/upload/article/001/503/042/175306875734691.jpg)
通过上面的操作,我们可以看出,通过配置文件来实现AOP操作时,首先创建类的对象,然后进行配置aop的操作:配置切入点和切面,配置切面的过程中可以配置前置增强、后置增强、环绕增强等增强类型。
二. 通过注解实现AOP操作
使用注解实现AOP操作,相对于配置文件的方式就简单了许多,只需3步就可以实现:
创建对象
<bean class="cn.itcast.aop.Book" id="book"></bean> <bean class="cn.itcast.aop.MyBook" id="myBook"></bean>
在Spring的核心配置文件中开启AOP操作
<aspectj-autoproxy></aspectj-autoproxy>
在增强的类上面使用注解完成AOP操作
@Aspect
public class MyBook {
//在方法上面使用注解完成增强配置
@Before(value="execution(<em> cn.itcast.aop.Book.</em>(..))")
public void before(){
System.out.println("before......");
}
}上面我们用注解实现了前置增强,类似这样的注解还有:@AfterReturning 后置增强、@Around 环绕增强等。
我们还可以看到,在上面两种方式实现AOP操作的过程中,都用到了这样的语句:”execution( cn.itcast.aop.Book.(..))”。这个就是execution表达式,用它可以帮助我们配置切入点。基本格式为:
execution(?(参数))
常用的execution表达式有:
*execution( cn.itcast.aop.Book.add(..))
访问修饰符包括private、public等,代表任意的修饰符。这个表达式的意思就是配置Book类的add方法为切入点。
execution( cn.itcast.aop.Book.(..))
Book类下面的所有方法都可以是切入点
execution( .(..))
任意类的任意方法是切入点
刚开始学习AOP,缺少项目经验,如果有不对的地方,还请大家多多指教。
发布者:全栈程序员栈长,转载请注明出处:https://www.php.cn/link/70b546d3daac16b1d8a1fc46e6d63a72
以上就是【spring】AOP实践[通俗易懂]的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号