Spring 的 AOP挺牛逼的,今天我就简单使用了一下
----------------------
什么是 AOP
----------------------
我理解的AOP就是使用动态代理,将业务逻辑和一些杂碎的事情分离开,让开发者专注于业务逻辑的开发
----------------------
为什么要用AOP
----------------------
假如我们要写注册用户 删除用户 查询用户的业务逻辑,然后每次操作都要往数据库中写入日志
传统的做法就是在业务逻辑执行前加代码来写日志,这样我们就要写很多重复的代码,看着很烦
但是我们用Spring的AOP的话,就好办了
这里我们就举一个例子
假如我们要洗头
洗头之前需要先烧水,然后倒水到盆子里
我们关心的事情就只是洗头,烧水和倒水虽是必须要做的,但是我们不怎么需要关心
-------------------
怎么使用Spring 的 AOP
--------------------
首先我们定义一个类
就写了一个方法,我们只需要关注的事情
public class Car {
public void go(){
System.out.println("开始洗头,使劲搓");
}
}
然后再写一个类,定义之前之后要做的事情
public class CarLogger {
public void beforeRun(){
System.out.println("先烧水,然后倒水");
}
public void afterRun(){
System.out.println("把水倒掉");
}
}
然后这里是重点
<?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:p="http://www.springframework.org/schema/p"
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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"
>
<bean id="car" class="Car"/>
<bean id="logger" class="CarLogger" />
<aop:config>
<aop:aspect ref="logger">
<aop:pointcut expression="execution(* Car.go(..))" id="go"/>
<aop:before pointcut-ref="go" method="beforeRun" />
<aop:after pointcut-ref="go" method="afterRun" />
<aop:around method="aroundRunder" pointcut-ref="go"/>
</aop:aspect>
</aop:config>
</beans>
我们写了一个xml
将两个类都用bean包裹起来放到了xml里
<aop:aspect ref="logger">
</aop:aspect>
这里指定了之后要做的事情的类的id
<aop:pointcut expression="execution(* Car.go(..))" id="go"/>
这里就定义了一个切面(Car类中的go()方法)并指定这个切面id为go
然后
<aop:before pointcut-ref="go" method="beforeRun" />
这里就是为id为go的切面指定之前要运行的方法
<aop:after pointcut-ref="go" method="afterRun" />
这个就是之后要执行的方法了
感谢您收看,再见