AOP
2017-05-15 本文已影响0人
maomizone
AOP
面向切面编程 Aspect-Oriented-Programming
优点
动态代理,不用修改原有的代码
Ex
/**
* Created by admin on 2017/5/15.
* AOP的实现 动态代理
*/
public class LogInterceptor implements InvocationHandler {
private Object target;
public void setTarget(Object target) {
this.target = target;
}
private void beforeMethod(Method method){
System.out.println(method.getName() + " start");
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
beforeMethod(method);
method.invoke(target, args);
return null;
}
}
/**
* Created by admin on 2017/5/3.
*/
public class UserServiceTest {
@Test
public void testProxy(){
UserDao userDao = new UserDaoMySqlImpl();
LogInterceptor li = new LogInterceptor();
li.setTarget(userDao);
UserDao proxy = (UserDao)Proxy.newProxyInstance(userDao.getClass().getClassLoader(),
new Class[]{UserDao.class}, li);
User user = new User("韩梅梅", 18);
proxy.save(user);
proxy.delete();
}
}
image.png