这个事是试过程中非常重要的一部分~~
1、简介
所谓AOP就是利用面向切面编程的原理,在程序中的一个方法执行的时候,将一个公用方法加入进去,比如记录操作时间的方法。如果不使用AOP这种方法,就必须用组合的方式,而组合会造成代码的大量重复。
AOP的主要就是就是Spring利用动态代理的方式进行实现,现给出一个小例子说明,具体代码如下:
2、定义user类
package proxy;
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
3、定义IUserDAO类
package proxy;
public interface IUserDAO {
public void save(User user);
public void delete();
}
4、定义UserDAOImpl类
package proxy;
public class UserDAOImpl implements IUserDAO {
@Override
public void save(User user) {
// TODO Auto-generated method stub
System.out.println("user saved !");
}
@Override
public void delete() {
// TODO Auto-generated method stub
System.out.println("user delete !");
}
}
5、定义LogInterceptor类
package proxy;
import java.lang.reflect.Method;
public class LogInterceptor {
public static void beforMethod(Method m){
if(m.getName().equals("save")){
System.out.println("save start time is :"+new Date());
}else if(m.getName().equals("delete")){
System.out.println("delete start time is :"+new Date());
}else{
System.out.println("没有找到对应的方法!");
}
}
}
6、定义LogInterceptorProxy类
package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import proxy.LogInterceptor;
public class LogInterceptorProxy implements InvocationHandler{
//可以将参数传入进来,也可以在这定义一个对象,如下所示
private Object target;
public Object getTarget() {
return target;
}
public void setTarget(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
LogInterceptor.beforMethod(m);
m.invoke(target, args);
return null;
}
}
7、测试类
package proxy;
import java.lang.reflect.Proxy;
import org.junit.Test;
import proxy.UserDAOImpl;;
public class UserServiceTest {
@Test
public void testProxy(){
IUserDAO userDAO = new UserDAOImpl();
LogInterceptorProxy li = new LogInterceptorProxy();
li.setTarget(userDAO);
IUserDAO userDAOProxy = (IUserDAO) Proxy.newProxyInstance(userDAO.getClass().getClassLoader(), userDAO.getClass().getInterfaces(), li);
userDAOProxy.save(new User());
userDAOProxy.delete();
}
}
8、输出结果:
save start time is :Thu Apr 11 22:26:58 CST 2013
user saved !
delete satart time is :Thu Apr 11 22:26:58 CST 2013
user delete !