在前面曾经有过AOP的Annotation方式的实现,现在要把它使用XML的方式实现
首先,切面类:
public class LogInterceptor {
public void myMethod(){}
public void beforeMethod(){
System.out.println("method before");
}
public void afterMethod(){
System.out.println("method after");
}
public void afterReturning(){
System.out.println("method after returning");
}
public void afterThrowing(){
System.out.println("method throws exception");
}
public void around(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("method around start");
pjp.proceed();
System.out.println("method around end");
}
}
bean.xml文件配置:
<?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-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-2.5.xsd">
<context:annotation-config />
<context:component-scan base-package="com.bjsxt"/>
<bean id="logInterceptor" class="com.bjsxt.aop.LogInterceptor"></bean>
<aop:config>
<aop:pointcut expression="execution(public * com.bjsxt.dao..*.*(..))" id="myPointcut"/>
<aop:aspect id="myAspect" ref="logInterceptor">
<aop:before method="beforeMethod" pointcut-ref="myPointcut" />
<aop:after method="afterMethod" pointcut-ref="myPointcut"/>
<aop:after-returning method="afterReturning" pointcut-ref="myPointcut"/>
<aop:around method="around" pointcut="execution(public * com.bjsxt.dao..*.*(..))"/>
</aop:aspect>
</aop:config>
</beans>
其中<aop:comfig>定义的是aop配置
<aop:pointcut>定义的是切点,其定义在config的第一层子目录,可以被其他所有的aspect所引用;当然pointcut还可以定义在<aop:aspect>的子目录,但是此时只能被该aspect所引用;id定义的是该pointcut的名字;<aop:pointcut>可以单独定义,也可以使用 <aop:around >中所示的定义方法
<aop:aspect>定义的切面,id是指该切面的名字,ref指的是它所引用的切面类
<aop:before>等通知中的method指的是其所位于的aspect所引用的切面类中的方法名,pointcut-ref指的是引用的切点