小编典典

从对象本身获取AOP代理

spring

可以在Spring中获取给定对象的代理吗?我需要调用子类的函数。但是,很明显,当我直接拨打电话时,这些方面均未应用。这是一个例子:

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");
    }
}

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

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);
    }
}

阅读 754

收藏
2020-04-13

共1个答案

小编典典

请考虑重构你的代码或使用AspectJ编织。你可能会感到警告,这是解决方案

AopContext.currentProxy()
2020-04-13