望着时间滴答滴答的流过,我不曾改变过 . . .

spring AOP

静态代理与动态代理

静态代理

/*
 *   created by why on 2020/3/1
 *
 * 代替UserServiceImpl代理 额外功能
 * 静态代理类
 *      1>  要和目标保持功能一致 : 和目标保持同一套接口
 *      2>  组成:目标 + 额外功能
 */

import com.baidu.pojo.User;

public class UserServiceProxy implements UserService{
    //原始业务:目标
    private UserService userService = new UserServiceImpl();

    public Integer insertUser(User user) {
        System.out.println("额外功能");
        return userService.insertUser(user);
    }

    public User queryOne(Integer id) {
        System.out.println("额外功能");
        return userService.queryOne(id);
    }
}

动态代理

    //动态代理搭建
        //1.目标
        final UserService userService = new UserServiceImpl();
        //2.额外功能
        InvocationHandler ih = new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                   //一个回调函数
                System.out.println("额外功能");
                method.invoke(userService,args);
                return null;
            }
        };
        //3.组装,编制
        //利用反射机制(动态生成反射出来的类),调用目标和额外,额外生成一个代理类
        UserService proxy = (UserService) Proxy.newProxyInstance(AppTest.class.getClassLoader(),
                userService.getClass().getInterfaces(),ih);
        proxy.queryOne(1);
        System.out.println("--------");
        proxy.insertUser(new User());

动态代理与AOP

动态代理的实现方案

1.jdk代理:(JDK在反射包中提供的一套api,上面的例子)通过和目标实现相同的接口保证功能的一致性
2.cglib代理:(第三方cglib库中的一套api)通过继承目标保证功能的一致性

spring aop

底层采用了如上的两种代理,并对动态代理提供了简单的,可操作强的决绝方案。
目标有接口吗?->有->用jdk代理,否则用cglib代理

切面:Aspect,由切入点额外功能组成。
一种新的编程角度:由 切面目标 形成代理。解决项目中的额外功能冗余的问题。

posted @ 2020-03-07 22:10  whyaza  阅读(124)  评论(0编辑  收藏  举报