SpringAOP通知(二)
XML配置形式
准备
目标类接口
public interface AopTest {
public String AopTestPrint();
}
目标类实现
@Component
public class AopTestImpl implements AopTest {
public String AopTestPrint() {
System.out.println("invoke AopTestPrint no arg method");
return null;
}
}
切面实现类
@Component
public class AspectsTest {
}
基础SpringXML配置
<?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"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
<!-- 需要引入aop和context 的约束 -->
<!-- 开启包扫描 -->
<context:component-scan base-package="com.test.springdome01"></context:component-scan>
<aop:config>
<!-- 定义切面 -->
<aop:aspect ref="aspectsTest">
<!-- 其中定义通知和切点 -->
</aop:aspect>
</aop:config>
</beans>
前置通知:Before
切面实现类添加前置通知
public void aopBefore(){
System.out.println("invoke aopBefore method");
}
xml增加前置通知
<aop:before method="aopBefore" pointcut="execution(String com.test.springdome01.AopTest.AopTestPrint(..))"></aop:before>
后置通知:After
切面实现类添加后置通知
public void aopAfter(){
System.out.println("invoke aopAfter method");
}
xml增加后置通知
<aop:after method="aopAfter" pointcut="execution(String com.test.springdome01.AopTest.AopTestPrint(..))"></aop:after>
返回通知:AfterRuturning
切面实现类添加返回通知
public void aopAfterReturning(){
System.out.println("invoke aopAfterReturning method");
}
xml增加返回通知
<aop:after-returning method="aopAfterReturning" pointcut="execution(String com.test.springdome01.AopTest.AopTestPrint(..))"></aop:after-returning>
异常通知:AfterThrowing
切面实现类添加异常通知
public void aopAfterThrowing(){
System.out.println("invoke aopAfterThrowing method");
}
xml增加异常通知
<aop:after-throwing method="aopAfterThrowing" pointcut="execution(String com.test.springdome01.AopTest.AopTestPrint(..))"></aop:after-throwing>
目标类中方法添加一个异常
int i = 1/0;
环绕通知:Around
切面实现类添加环绕通知
public void aopAround(ProceedingJoinPoint pj) throws Throwable {
System.out.println("invoke aopAround method1");
pj.proceed();
pj.proceed();
System.out.println("invoke aopAround method2");
}
xml增加环绕通知
<aop:around method="aopAround" pointcut="execution(String com.test.springdome01.AopTest.AopTestPrint(..))"></aop:around>