基于CGLIB代理的经典Spring Aop

经典的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...
注释:产生的代理对象被转换成了目标对象,可以猜测,代理对象继承了目标对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值