AOP实现方式

AOP实现方式

参考文章

原理:在ioc中创建了一个原对象的代理对象,而这个对象是AOP增强过的。
 

动态代理

JDK

1.1 实现接口

interface UserService{
    void add();
    void del();
}

1.2 原对象

class UserServiceImpl implements UserService {
    @Override
    public void add() {System.out.println("add");}
    @Override
    public void del() {System.out.println("del");}
}

1.3 创建 InvocationHandler 处理器

class MyInvocationHandler implements InvocationHandler {
    private Object target;
    public MyInvocationHandler(Object target){
        this.target = target;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before method");
        // 执行原对象方法
        Object res = method.invoke(target, args);
        System.out.println("after method");
        return res;
    }
}

1.4 使用

public static void main(String[] args) throws InterruptedException {
        // 创建并使用代理对象
        UserServiceImpl userService = new UserServiceImpl();
        MyInvocationHandler myInvocationHandler = new MyInvocationHandler(userService);
        UserService proxy = (UserService) Proxy.newProxyInstance(
                userService.getClass().getClassLoader(),
                userService.getClass().getInterfaces(),
                myInvocationHandler
        );
        proxy.add();
        proxy.del();
}
------------------------------------------------------
before method
add
after method
before method
del
after method

Process finished with exit code 0

 

CGLib

原理:CGLib直接操作字节码,生成类的子类,重写类的方法完成代理。

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇