Spring(十二)使用Spring的xml文件配置方式实现AOP

配置文件与注解方式的有很大不同,多了很多配置项。

beans2.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns=""xmlns:xsi="" xmlns:context=""xmlns:aop=""xsi:schemaLocation=" "> <aop:aspectj-autoproxy /> <bean id="personService" class="test.spring.service.impl.PersonServiceBean"></bean> <bean id="myInterceptor" class="test.spring.aop.MyInterceptor2"></bean> <aop:config> <aop:aspect id="myAspect" ref="myInterceptor"> <aop:pointcut id="myPointCut" expression="execution(* test.spring.service.impl.PersonServiceBean.*(..))" /> <aop:before pointcut-ref="myPointCut" method="doAccessCheck" /> <aop:after-returning pointcut-ref="myPointCut" method="doAfterReturning" /> <aop:after-throwing pointcut-ref="myPointCut" method="doAfterThrowing" /> <aop:around pointcut-ref="myPointCut" method="doAround" /> <aop:after pointcut-ref="myPointCut" method="doAfter" /> </aop:aspect> </aop:config></beans>

package test.spring.service.impl;import test.spring.service.PersonService;//代理对象实现目标对象所有接口public class PersonServiceBean implements PersonService {public PersonServiceBean() {}@Overridepublic void save(String name) {System.out.println("save()->>" + name);throw new RuntimeException(">>—-自定义异常—-<<");}@Overridepublic String getResult() {return "getResult()==>>返回结果";}}package test.spring.aop;import org.aspectj.lang.ProceedingJoinPoint;public class MyInterceptor2 {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 doAround(ProceedingJoinPoint pJoinPoint) throws Throwable {System.out.println("环绕通知");// 这里如果pJoinPoint.proceed()不执行,后面拦截到的方法都不会执行,非常适用于权限管理Object result = pJoinPoint.proceed();System.out.println("退出");return result;}}package test.spring.junit;import org.junit.Test;import org.springframework.context.support.AbstractApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import test.spring.service.PersonService;public class AOPTest3 {@Testpublic void test() {AbstractApplicationContext aContext = //new ClassPathXmlApplicationContext("beans2.xml");PersonService pService = (PersonService) aContext.getBean("personService");pService.save("LinDL");pService.getResult();aContext.close();}}

版权声明:本文为博主原创文章,,未经博主允许不得转载。如需转载,请注明出处:

当一个人真正觉悟的一刻,他放弃追寻外在世界的财富,而开始追寻他内心世界的真正财富

Spring(十二)使用Spring的xml文件配置方式实现AOP

相关文章:

你感兴趣的文章:

标签云: