什么是Aop
Aop全称:Aspect Oriented Programming,即面向切面编程。
Aop是一种通过运行期动态代理实现代码复用的机制,是对传统OOP(Object Oriented Programming,面向对象编程 )的补充。目前,Aspectj是Java社区里最完整最流行的AOP框架,在Spring 2.0以上版本中可以通过Aspectj注解或基于XML配置AOP。
为什么使用Aop
利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
(节省代码,提高代码复用性,便于开发)
如何使用Aop
第一步:拷jar包:
第二步:我们首先定义一个计算器类
//这里我们给上Service注解,从而扫描至IoC容器中
@Service
public class CalculatorService implements ICalculatorService{
public int mul(int a, int b){
return a*b;
}
public int div(int a, int b){
return a/b;
}
}
第三步:我们写一个切面类,增强方法有五种,会有一篇博客专门叙述,这里做了解即可
//这里Aspect声明该类为一个切面类
@Aspect
//将该类对象放入IoC容器中
@Component
public class CalculatorAspect{
//这是一个切入点,与之匹配的方法,则可以获得增强,这里的 * 为符合访问权限为public 返回值类型为int的所有方法,(..)为任意参数列表
@Pointcut("execution(public int live.sunhao.calculator.service.CalculatorService.*(..))")
public void pointcut() {
}
//前置增强(又称前置通知):在目标方法执行之前执行
@Before("pointcut()")
public void before(JoinPoint jp){
Object[] args = jp.getArgs();
Signature signature = jp.getSignature();
String name = signature.getName();
System.out.println("The "+name+" method begins.");
System.out.println("The "+name+" method args:["+args[0]+","+args[1]+"]");
}
}
第四步:配置xml文件,实现aop有两种方式,我们这里采用了自动代理实现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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<context:component-scan base-package="live.sunhao"></context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
第五步:写一个测试类
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
ICalculatorService calculatorService = applicationContext.getBean(ICalculatorService.class);
System.out.println(calculatorService.div(2, 2));
}
}
注意:这里的calculatorService是代理对象 class com.sun.proxy.$Proxy9
如果不在xml文件中设置自动代理的话,则为class live.sunhao.calculator.service.CalculatorService
控制台输出如下:
来源:CSDN
作者:S_Tian
链接:https://blog.csdn.net/S_Tian/article/details/104172485