【问题标题】:AOP with Local Variable Annotations带有局部变量注解的 AOP
【发布时间】:2010-07-23 23:46:39
【问题描述】:

我想使用局部变量注解来做更好的 AOP。一种想法是通过使用注解的代理来实现 Future 概念。

@NonBlocking ExpensiveObject exp = new ExpensiveObject(); 
//returns immediately, but has threaded out instantiation of the ExpensiveObject.

exp.doStuff(); 
//okay, now it blocks until it's finished instantiating and then executes #doStuff

我能否以某种方式让 AspectJ 生病并使用局部变量注释来完成我想要的工作?我知道其他线程表明 Java 并不真正支持它们,但它会很神奇。我真的不想传递 Future 并破坏封装。

【问题讨论】:

    标签: java annotations aop aspectj


    【解决方案1】:

    你不能使用代理来做到这一点,但如果你注释类型而不是局部变量,真正的 aspectj 字节码编织将让你到达那里。 (我认为不支持将局部变量访问作为切入点)。不管怎样,这里有一些代码。

    注释:

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    public @interface Later {}
    

    用这个注解标记的类:

    package com.dummy.aspectj;
    @Later
    public class HeavyObject{
    
        public HeavyObject(){
            System.out.println("Boy, I am heavy");
        }
    }
    

    一个主类:

    package com.dummy.aspectj;
    public class HeavyLifter{
    
        public static void main(final String[] args){
            final HeavyObject fatman = new HeavyObject();
            System.out.println("Finished with main");
        }
    
    }
    

    还有一个方面:

    package com.dummy.aspectj;
    public aspect LaterAspect{
    
        pointcut laterInstantiation() :
            execution(@Later *.new(..))    ;
    
        void around() : laterInstantiation() {
            new Thread(new Runnable(){
                @Override
                public void run(){
                    System.out.println("Wait... this is too heavy");
    
                    try{
                        Thread.sleep(2000);
                    } catch(final InterruptedException e){
                        throw new IllegalStateException(e);
                    }
                    System.out.println("OK, now I am up to the task");
                    proceed();
                }
            }).start();
        }
    
    }
    

    当您将 HeavyLifter 作为 Eclipse 中的 AspectJ/Java 应用程序运行时,以下是其输出:

    Finished with main
    Wait... this is too heavy
    OK, now I am up to the task
    Boy, I am heavy
    

    【讨论】:

    • 在考虑了您的解决方案之后,我意识到它可能比内联分配 @nonblocking 更好,因为它应该是对象固有的知道这是“重”。所以我暂时满意了……谢谢!
    猜你喜欢
    • 2013-05-06
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 2013-04-30
    相关资源
    最近更新 更多