您的位置:首页 > 编程语言 > Java开发

Spring3核心技术之AOP配置

2020-06-04 07:02 337 查看
在Spring配置文件中,所有AOP相关定义必须放在<aop:config>标签下,该标签下可以有<aop:pointcut>、<aop:advisor>、<aop:aspect>标签,配置顺序不可变。


● <aop:pointcut>:用来定义切入点,该切入点可以重用;
● <aop:advisor>:用来定义只有一个通知和一个切入点的切面;
● <aop:aspect>:用来定义切面,该切面可以包含多个切入点和通知,而且标签内部的通知和切入点定义是无序的;和advisor的区别就在此,advisor只包含一个通知和一个切入点。

public class Interceptor {

public void beforeDomain() {
System.out.println("This is beforeDomain....");
}

public void afterDomain() {
System.out.println("This is afterDomain....");
}

public void afterReturning() {
System.out.println("This is afterReturning....");
}

public void afterThrowing() {
System.out.println("This is afterThrowing....");
}

public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("===========around before advice");
Object retVal = pjp.proceed(new Object[] {"【环绕通知】"});
System.out.println("===========around after advice");
return retVal;
}
}
[/code]
.....

<bean id="aspectBean" class="com.chou.spring.domain.Interceptor"/>

<aop:config proxy-target-class="false">
<aop:aspect ref="aspectBean">
<!-- 定义切入点 -->
<aop:pointcut id="myAspect"
expression="execution(public * com.chou.spring.bean..*.domain(..))" />

<!-- 前置通知 -->
<aop:before pointcut-ref="myAspect" method="prepareDomain"/>

<!-- 后置通知 -->
<aop:after-returning pointcut-ref="myAspect" method="afterReturning"/>
<aop:after-throwing pointcut-ref="myAspect" method="afterThrowing"/>
<aop:after pointcut-ref="myAspect" method="afterDomain"/>

<!-- 环绕通知 -->
<aop:around method="around"
pointcut="execution(* com.chou.spring.bean..*.sayAround(..))"/>
</aop:aspect>
</aop:config>

public interface MyBean {
public void domain();
}

public class MyBeanA{
public void domain() {
System.out.println("MyBeanA is executing...");
}

public void sayAround(String param) {
System.out.println("around param:" + param);
}
}

public class MyBeanB implements MyBean{
public void domain() {
System.out.println("MyBeanB is executing...");
//throw new RuntimeException("This is a RuntimeException");
}
}

//main方法....
String[] configs = new String[] {"applicationContext-aop.xml"};
ApplicationContext cxt = new ClassPathXmlApplicationContext(configs);
//如果Bean有interface那么就用JDK的Proxy.newProxyInstance得到代理对象进行aop
MyBean b = (MyBean)cxt.getBean("beanB");
b.domain();
//如果Bean没有实现任何interface那么就用CGLIB得到代理对象进行aop
MyBeanA a = cxt.getBean("beanA",MyBeanA.class);
a.domain();
a.sayAround("jjjjjjjjjjjjjjjjjjj");
[/code]

<aop:before pointcut="切入点表达式"  pointcut-ref="切入点Bean引用"
method="前置通知实现方法名" arg-names="前置通知实现方法参数列表参数名字"/>

<aop:after-throwing pointcut="切入点表达式"  pointcut-ref="切入点Bean引用"
method="后置异常通知实现方法名"
arg-names="后置异常通知实现方法参数列表参数名字"
throwing="将抛出的异常赋值给的通知实现方法参数名"/>

<aop:around pointcut="切入点表达式"  pointcut-ref="切入点Bean引用"
method="后置最终通知实现方法名"
arg-names="后置最终通知实现方法参数列表参数名字"/>

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: