- 论坛徽章:
- 0
|
关于AOP我只知道它是干嘛的,对于它的原理我是很迷糊的
为了理解它,就先写了一个简单的测试
把Spring的类库放到ClassPath里
首先要写一个接口,因为我测试的代理目标是接口,所以我要先写出一个接
//SayHello.java
package com.aop
public interface SayHello {
void hello();
}
然后给出它的一个实现
//SayHelloImpl.java
package com.aop
public class SayHelloImpl implements SayHello {
public void hello()
{
System.out.println("Hello method invoked!");
}
}
下面就要写出一个实现了MethodBeforeAdvice接口的类来实现AOP
//MethodBeforeSayHello.java
package com.aop;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class MethodBeforeSayHello implements MethodBeforeAdvice {
public void before(Method arg0, Object[] arg1, Object arg2)
throws Throwable {
System.out.println("This is the method before hello() method!");
}
}
配置一下XML
com.aop.SayHello
methodBefore
然后写一个测试类测试一下,假设我把这个XML文件放到C盘目录下
package com.aop;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class SimpleTest {
public static void main(String[] args)
{
String filePath="c:\\applicationContext.xml";//这里就是XML文件绝对路径
BeanFactory factory = new XmlBeanFactory(new FileSystemResource(filePath));
SayHello say = (SayHello)factory.getBean("sayHello");
say.hello();
}
}
输出结果是
This is the method before hello() method!
hello method invoked!
//SayHello.java
package com.aop
public interface SayHello {
void hello();
}
//SayHello.java
package com.aop
public interface SayHello {
void hello();
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/63740/showart_513217.html |
|