这里使用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