从对象本身获取 AOP 代理 [英] Get AOP proxy from the object itself

查看:21
本文介绍了从对象本身获取 AOP 代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Spring 中获取给定对象的代理?我需要调用子类的函数.但是,很明显,当我直接调用时,这些方面没有被应用.举个例子:

Is possible to get the proxy of a given object in Spring? I need to call a function of a subclass. But, obviously, when I do a direct call, the aspects aren't applied. Here's an example:

public class Parent {

    public doSomething() {
        Parent proxyOfMe = Spring.getProxyOfMe(this); // (please)
        Method method = this.class.getMethod("sayHello");
        method.invoke(proxyOfMe);
    }
}

public class Child extends Parent {

    @Secured("president")
    public void sayHello() {
        System.out.println("Hello Mr. President");
    }
}

我找到了实现这一目标的方法.它有效,但我认为不是很优雅:

I've found a way of achieving this. It works, but I think is not very elegant:

public class Parent implements BeanNameAware {

    @Autowired private ApplicationContext applicationContext;
    private String beanName; // Getter

    public doSomething() {
        Parent proxyOfMe = applicationContext.getBean(beanName, Parent.class);
        Method method = this.class.getMethod("sayHello");
        method.invoke(proxyOfMe);
    }
}

推荐答案

这个 hack 非常尴尬,请考虑重构您的代码或使用 AspectJ 编织.您可能会感到受到警告,这是解决方案

This hack is extremely awkward, please consider refactoring your code or using AspectJ weaving. You may feel warned, here is the solution

AopContext.currentProxy()

JavaDoc.我在这里这里.

这篇关于从对象本身获取 AOP 代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆