Spring AOP编程
Posted SparkQuant
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring AOP编程相关的知识,希望对你有一定的参考价值。
AOP:面向切面编程
Spring的AOP编程,分为Schema-base和AspectJ,本篇为介绍Schema-base,
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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="mybefore" class="com.fd.advice.MyBeforeAdvice"></bean> <bean id="myafter" class="com.fd.advice.MyAfterAdvice"></bean> <aop:config> <aop:pointcut expression="execution(* com.fd.test.Demo.*(..))" id="mypoint"/> <aop:advisor advice-ref="mybefore" pointcut-ref="mypoint"/> <aop:advisor advice-ref="myafter" pointcut-ref="mypoint"/> </aop:config> <bean id="demo" class="com.fd.test.Demo"></bean> </beans>
关于AOP的配置都在<aop:config></aop:config>中, 其中<aop:pointcut expression="execution(* com.fd.test.Demo.*(..))" id="mypoint"/>定义的是切面 *是通配符
<aop:advisor advice-ref="mybefore" pointcut-ref="mypoint"/>和<aop:advisor advice-ref="myafter" pointcut-ref="mypoint"/>定义的是切面方法,其中MyBeforeAdvice和MyAfterAdvice需要
分别继承接口MethodBeforeAdvice、AfterReturnAdvice,
具体代码如下:
package com.fd.advice; import java.lang.reflect.Method; import org.springframework.aop.MethodBeforeAdvice; public class MyBeforeAdvice implements MethodBeforeAdvice { @Override public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable { System.out.println("Before Method Advice" + arg0); } }
package com.fd.advice; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; public class MyAfterAdvice implements AfterReturningAdvice{ @Override public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable { System.out.println("After returning advice..."); } }
package com.fd.test; public class Demo { public void demo1() { System.out.println("demo1"); } public void demo2(String para) { System.out.println("demo2"); } public void demo3() { System.out.println("demo3"); } }
package com.fd.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestDemo { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); Demo demo = ac.getBean("demo", Demo.class); demo.demo1(); demo.demo2("aad"); demo.demo3(); } }
运行结果如下,可以看到在demo1、demo2、demo3方法的前后都增加了切面函数
以上是关于Spring AOP编程的主要内容,如果未能解决你的问题,请参考以下文章