接口类
-
public
interface User {
-
public void work();
-
}
具体实现类
-
public
class IUser implements User {
-
-
public void work() {
-
System.out.println(
"-------工作ing----------");
-
}
-
-
}
切面类
-
public void doBefore() {
-
System.
out.println(
"-------1.执行前通知--------");
-
}
-
public void doAfterReturning() {
-
System.
out.println(
"-------2.执行无异常后通知--------");
-
}
-
public Object Around(ProceedingJoinPoint p) throws Throwable {
-
System.
out.println(
"----------3.环绕通知前-------");
-
Object proceed = p.proceed();
-
System.
out.println(
"----------3.环绕通知后--");
-
return p;
-
}
-
public void AfterThrowing() {
-
System.
out.println(
"--------4.执行后出现异常通知+-----");
-
}
-
-
public void After() {
-
System.
out.println(
"-------5.执行方法后无论是否出现异常均执行----finally");
-
}
注意执行环绕通知时 使用 ProceedingJoinPoint 获取执行的方法信息
配置文件
-
<!-- 声明一个业务类既代理的对象 -->
-
<bean id="IUser" class="AOP2.IUser">
</bean>
-
<!-- 声明一个通知类既切面 -->
-
<bean id="MyProxy" class="AOP2.MyProxy">
</bean>
-
-
<aop:config>
-
<!--声明具体通知类的配置 -->
-
<aop:aspect ref="MyProxy">
-
<aop:pointcut expression="execution(* AOP2.IUser.*(..))" id="pointcut"/>
-
-
<aop:before method="doBefore" pointcut-ref="pointcut"/>
-
<aop:after method="After" pointcut-ref="pointcut"/>
-
<aop:after-returning method="doAfterReturning" pointcut-ref="pointcut" returning="result"/>
-
<aop:after-throwing method="AfterThrowing" pointcut-ref="pointcut" throwing="ex"/>
-
<aop:around method="Around" pointcut-ref="pointcut"/>
-
</aop:aspect>
-
</aop:config>
测试类
-
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext(
"spring.xml");
-
User user = (User) context.getBean(
"IUser");
//注意声明的类为接口
-
user.work();
//以JDK代理实现AOP功能
方法二:注解实现
切面类
-
@Pointcut("execution(* AOP.IUser.*(..))")
-
public void pointCut() {
-
-
}
-
@Before("pointCut()")
-
public void doBefore() {
-
System.
out.println(
"-------1执行前通知--------");
-
}
-
@AfterReturning("pointCut()")
-
public void doAfter() {
-
System.
out.println(
"-------2执行无异常后通知--------");
-
}
-
@After("pointCut()")
-
public void doEnd() {
-
System.
out.println(
"---------3执行后最终通知--不管是否发生异常都执行-----");
-
}
-
@Around("pointCut()")
-
public Object doAround(ProceedingJoinPoint p) throws Throwable {
-
System.
out.println(
"----------5.环绕通知开始---------");
-
Object proceed = p.proceed();
-
System.
out.println(
"----------5.环绕通知结束----------");
-
return p;
-
}
-
@AfterThrowing("pointCut()")
-
public void doError() {
-
System.
out.println(
"------------4执行异常通知----------");
-
}
注意使用@PointCut声明切点
测试类
-
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext(
"spring.xml");
-
IUser user = (IUser) context.getBean(
"IUser");
-
user.work();
注意:
- Target 目标对象既具体的业务类
- proxy 代理对象既 通知类或切面类
- pointcut 切点 业务类中某个方法进行拦截的方法
- jionpoint 连接点 业务类中所有方法
- 如果目标对象没有实现接口则使用CGLIB代理,有关设置为<aop:aspectj-autoproxy proxy-target-class="true">,实现接口则使用JDK代理,默认为JDK代理.
- 声明切点的方法可以为 execution(* AOP.IUser.*(..))
- execution()表明主题类
- 第一个* 表示返回类型任意
- 包名
- 第一个. 代表此包 第二个.为此包下的所有子包 (这里没有写第二个.)
- *(..)代表所有类中所有方法
- (..)类中所有方法