经过这段日子的学习和使用Spring,慢慢地体会到Spring的优妙之处,正在深入地吸收Spring的精华,呵呵。现在写的这个只是个简单AOP例子,包括前置通知,后置通知,环绕通知,和目标对象。写这个例子的主要目标只是想让想学AOP的能更快地入门,了解一下如何去配置AOP里面的东东。
目标对象的接口:IStudent.java
package com.test.logging;
public interface IStudent {
public void addStudent(String name);
}
目标类:StudentImpl.java
package com.test.logging;
public class StudentImpl implements IStudent {
public void addStudent(String name) {
System.out.println(" 欢迎 " + name + " 你加入Spring家庭! ");
}
}
前置通知:BeforeAdvice.java
package com.test.logging;
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方法. ");
}
}
后置通知:AfterAdvice.java
package com.test.logging;
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方法.");
}
}
环绕通知:CompareInterceptor.java
package com.test.logging;
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")) {
result = invocation.proceed();
} else {
System.out.println("此学生是" + stu_name + "而不是dragon,不批准其加入.");
}
return result;
}
}
配置文件applicationContext.xml
<bean id="beforeAdvice" class="com.test.logging.beforeAdvice"></bean>
<bean id="afterAdvice" class="com.test.logging.afterAdvice"></bean>
<bean id="compareInterceptor" class="com.test.logging.compareInterceptor"></bean>
<bean id="studenttarget" class="com.test.logging.StudentImpl"></bean>
<bean id="student" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.test.logging.IStudent</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>
现在开始写测试类,Test.java
package com.test.logging;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class test {
public static void main(String[] args) {
ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:applicationContext.xml");
IStudent person = (IStudent) ctx.getBean("student");
person.addStudent("dragon");
}
}
原文地址:http://www.blogjava.net/javadragon/archive/2006/12/03/85115.html