這裏使用Aspectj來實現AOP。使用AOP會用到代理。有兩種代理:
jdk代理:只能代理實現了接口的類。
CGLIB代理:不只能夠對實現接口的類進行代理,同時也能夠對類自己生成代理(主要是經過繼承這個類來生成的,因此不要將要代理的類設成final) java
1、所需jar包 node
aopalliance.jar aspectjrt.jar aspectjweaver.jar cglib-nodep-2.1_3.jar commons-collections.jar commons-logging.jar spring-aop.jar spring-beans.jar spring-context.jar spring-core.jar2、自定義切面類
package aop; import org.aspectj.lang.JoinPoint; /** * 自定義的切面 * @author Cabriel * */ public class MyAspect { public void doBefore(JoinPoint jp){ System.out.println("log begin method: "+jp.getTarget().getClass().getName()+"."+jp.getSignature().getName()); } public void doAfter(JoinPoint jp){ System.out.println("log end method: "+jp.getTarget().getClass().getName()+"."+jp.getSignature().getName()); } }3、須要AOP的類
package service; public class MyBService { public void foo(){ System.out.println("do foo method in mybservice..."); } }
四:spring配置 spring
<?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-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <aop:config> <aop:aspect id="MyAspect" ref="aspectBean"> <aop:pointcut id="bisService" expression="execution(* service..*.*(..))"/> <aop:before pointcut-ref="bisService" method="doBefore"/> <aop:after pointcut-ref="bisService" method="doAfter"/> </aop:aspect> </aop:config> <bean id="aspectBean" class="aop.MyAspect"/> <bean id="mybservice" class="service.MyBService"/> </beans>5、測試類
package main; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import service.MyBService; public class MyTest { /** * @param args */ public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); MyBService bservice = (MyBService)ctx.getBean("mybservice"); bservice.foo(); } }打印結果
log begin method: service.MyBService.foo do foo method in mybservice... log end method: service.MyBService.foo