(资料图片仅供参考)
1.声明schema,导入命名空间
(1)如果我们想要使用基于xml的spring aop,那么,第一步,我们需要在xml配置文件中声明spring aop schema,导入命名空间,如下这是一个标准的模板
(2)在xml配置文件中,所有的切面以及通知等都必须放置于标签内
2.声明一个切面
//定义一个切面类Logger,在其中声明一个前置通知public class Logger { public void beforePrint() { System.out.println("before..."); }}
3.声明一个切入点
4.声明一个通知
//切面类public class Logger { public void beforePrint() { System.out.println("before..."); } public void afterReturningPrint(Object returnVal) { System.out.println(returnVal); System.out.println("afterReturning..."); } public void afterThrowingPrint(Throwable throwable) { System.out.println(throwable); System.out.println("afterThrowing..."); } public void afterPrint() { System.out.println("after..."); } public void aroundPrint(ProceedingJoinPoint joinPoint) { try { System.out.println("before..."); joinPoint.proceed(); System.out.println("after..."); } catch (Throwable throwable) { throwable.printStackTrace(); } finally { System.out.println("finally..."); } }}
5.优先级
6.声明一个引介
public class ExampleA{}//希望向ExampleA中添加方法doSomething()public interface Extention { void doSomething();}//doSomething()方法默认的实现public class ExtentionImpl implements Extention{ @Override public void doSomething() { System.out.println("doSomething..."); }} //使用引介,与基于注解的配置一致Extention exampleA = (Extention)ctx.getBean("exampleA");
7.Advisors
(1) 除了使用标签外,我们还可以使用标签来声明一个切面,不过使用时,其所指向的bean必须要实现对应的Advice接口,如下
//若要定义前置通知,则必须实现MethodBeforeAdvice接口,其他相应的通知也有对应的接口public class Logger implements MethodBeforeAdvice { @Override public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println("advisor before..."); }}
关键词: