package aop; /** * 目标对象的接口 */ public interface Student { public void addStudent(String name); }
package aop; /** * 目标对象 */ public class StudentImpl implements Student { public void addStudent(String name) { System.out.println(" 欢迎 " + name + " 你加入Spring家庭! "); } }
package aop; import java.lang.reflect.Method; import org.springframework.aop.MethodBeforeAdvice; /** * 前置通知 */ public class BeforeAdvice implements MethodBeforeAdvice { public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println(" 这是BeforeAdvice类的before方法. "); } }
package aop; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; /** * 后置通知 */ public class AfterAdvice implements AfterReturningAdvice { public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { System.out.println("这是AfterAdvice类的afterReturning方法."); } }
package aop; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; /** * 环绕通知 */ public class CompareInterceptor implements MethodInterceptor { public Object invoke(MethodInvocation invocation) throws Throwable { Object result = null; String stu_name = invocation.getArguments()[0].toString(); if (stu_name.equals("dragon")) { // 如果学生是dragon时,执行目标方法, result = invocation.proceed(); } else { System.out.println("此学生是" + stu_name + "而不是dragon,不批准其加入."); } return result; } }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="beforeAdvice" class="aop.BeforeAdvice"></bean> <bean id="afterAdvice" class="aop.AfterAdvice"></bean> <bean id="compareInterceptor" class="aop.CompareInterceptor"></bean> <bean id="studenttarget" class="aop.StudentImpl"></bean> <bean id="student" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces"> <value>aop.Student</value> </property> <property name="interceptorNames"> <list> <value>beforeAdvice</value> <value>afterAdvice</value> <value>compareInterceptor</value> </list> </property> <property name="target"> <ref bean="studenttarget" /> </property> </bean> </beans>
package aop; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; /** * 测试代码 */ public class Test { public static void main(String[] args) { ApplicationContext ctx = new FileSystemXmlApplicationContext("/src/applicationContext.xml"); Student s = (Student)ctx.getBean("student"); s.addStudent("aaa"); } }