AOP

作者: maomizone | 来源:发表于2017-05-15 17:24 被阅读0次

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

相关文章

网友评论

      本文标题:AOP

      本文链接:https://www.haomeiwen.com/subject/imlhxxtx.html