Spring XML配置实现AOP

时间:2024-01-05 23:11:20

1:  首先我们要定义 配置成切面的类

package cn.gbx.example;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut; public class MyXmlIntercept { public void doAccessCheck() { System.out.println("前置通知");
} public void doAfterReturning() {
System.out.println("后置通知");
} public void doAfter() {
System.out.println("最终通知");
} public void doAfterThrowing() {
System.out.println("例外通知");
} public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("进入方法");
Object value = pjp.proceed();
System.out.println("退出方法");
return value;
}
}

  

然后再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: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-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"> <aop:aspectj-autoproxy/> <bean id="personService" class="cn.gbx.serviceimpl.PersonServiceImpl"></bean> <bean id="myXmlIntercept" class="cn.gbx.example.MyXmlIntercept"></bean>
<aop:config>
<aop:aspect id="myasp" ref="myXmlIntercept">
<aop:pointcut expression="execution (* cn.gbx.serviceimpl.PersonServiceImpl.*(..))" id="mycut"/>
<aop:before method="doAccessCheck" pointcut-ref="mycut"/>
<aop:after-returning pointcut-ref="mycut" method="doAfterReturning"/>
<aop:after-throwing pointcut-ref="mycut" method="doAfterThrowing"/>
<aop:after pointcut-ref="mycut" method="doAfter"/>
<aop:around pointcut-ref="mycut" method="doBasicProfiling"/>
</aop:aspect>
</aop:config>
</beans>

  

然后测试即可。

简单说明

 expression="execution (* cn.gbx.serviceimpl.PersonServiceImpl.*(..))"
如果我们要要返回值烈性为Stirng的 方法才被拦截
execution (java.lang.String cn.gbx.serviceimpl.PersonServiceImpl.*(..))

如果我们要求参数第一个为String , 后边不限
expression="execution (* cn.gbx.serviceimpl.PersonServiceImpl.*(java.lang.String, ..))"

要求返回至为非void
expression="execution (!void cn.gbx.serviceimpl.PersonServiceImpl.*(..))"