经典的Spring Aop可以基于JDK动态代理,也可以基于CGLIB(Code Generation Library)代理。
创建基于JDK的动态代理时,只有在目标对象所实现的接口里声明了的方法才会经过代理,也就是说,目标对象必须至少实现一个接口。但是基于CGLIB代理的Aop,目标对象可以不必实现任何接口。
在经典的Spring Aop中,如果目标Bean没有实现任何接口,那么ProxyFactoryBean将创建CGLIB代理,CGLIB可以代理目标对象里的所有方法。
目标类:
package com.zzj.aop;
public class Human{
public void eat() {
System.out.println("eat...");
}
}
前置通知:
package com.zzj.aop;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class MethodBefore implements MethodBeforeAdvice {
public void before(Method arg0, Object[] arg1, Object arg2)
throws Throwable {
System.out.println("before...");
}
}
后置通知:
package com.zzj.aop;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class MethodAfter implements AfterReturningAdvice {
public void afterReturning(Object arg0, Method arg1, Object[] arg2,
Object arg3) throws Throwable {
System.out.println("after...");
}
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 定义目标对象 -->
<bean id="human" class="com.zzj.aop.Human"></bean>
<!-- 定义通知 -->
<bean id="before" class="com.zzj.aop.MethodBefore"></bean>
<bean id="after" class="com.zzj.aop.MethodAfter"></bean>
<!-- 定义代理对象 -->
<bean id="humanProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 指定目标对象 -->
<property name="target" ref="human"></property>
<!-- 指定拦截器(通知) -->
<property name="interceptorNames">
<list>
<value>after</value>
<value>before</value>
</list>
</property>
</bean>
</beans>
测试:
package com.zzj.aop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Human human = (Human) context.getBean("humanProxy");
human.eat();
}
}
输出:
before...
eat...
after...
注释:产生的代理对象被转换成了目标对象,可以猜测,代理对象继承了目标对象。