我们知道,要使用JDK的动态代理,目标类需要实现至少一个接口,下面定义了一个接口:
目标类:
前置通知:
后置通知:
spring配置文件:
测试:
输出:
特别注意:只有调用在接口里声明的方法才会经过代理。ProxyFactoryBean为目标对象创建了一个代理对象,并在IOC容器里注册了它。默认情况下,ProxyFactoryBean自动侦测并且代理目标对象所实现的所有接口,所以,如果想代理目标对象的所有接口,可以不必显示地指定这些接口。代理Bean可如下配置:
- package com.zzj.aop;
- public interface Animal {
- public void eat();
- }
- package com.zzj.aop;
- public class Human implements Animal {
- @Override
- 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...");
- }
- }
- <?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="interfaces">
- <list>
- <value>com.zzj.aop.Animal</value>
- </list>
- </property>
- <!-- 指定目标对象 -->
- <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");
- Animal animal = (Animal) context.getBean("humanProxy");
- animal.eat();
- }
- }
- before...
- eat...
- after...
- <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>