2015-10-01 39 views
2

获得注释的对象我有一个这样的注释:如何使用AspectJ

@Inherited 
@Documented 
@Target(value={ElementType.TYPE}) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface Restful { 

} 

我注释这个类是这样的:

@Restful 
public class TestAspect { 
    public String yes; 
} 

我有一个切入点是这样的:

@Pointcut("@annotation(com.rest.config.Restful)") 
    public void pointCutMethod() { 
} 

我试过了:

@Before("pointCutMethod()") 
public void beforeClass(JoinPoint joinPoint) { 
    System.out.println("@Restful DONE"); 
    System.out.println(joinPoint.getThis()); 
} 

但getThis()返回null。

基本上我试图得到TestAspect的对象实例。我该怎么做?任何线索?任何帮助将非常感激。

在此先感谢

回答

1

有了您的注释放在只有类型和切入点@annotation(com.rest.config.Restful)你只打算以匹配静态初始化连接点的类型。正如我们可以看到,如果你使用-showWeaveInfo当你编译(我掴你的代码样本到一个名为Demo.java文件):

Join point 'staticinitialization(void TestAspect.<clinit>())' in 
    Type 'TestAspect' (Demo.java:9) advised by before advice from 'X' (Demo.java:19) 

当静态初始化运行没有this,因此你会得到空当您检索它从thisJoinPoint。你没有说你真正想要建议的,但让我假设它是创建一个TestAspect的新实例。你的切入点需要匹配的构造函数执行此注释类型:

// Execution of a constructor on a type annotated by @Restful 
@Pointcut("execution((@Restful *).new(..))") 
public void pointcutMethod() { } 

如果你想匹配该类型的方法,这将是这样的:

@Pointcut("execution(* (@Restful *).*(..))") 
+0

感谢@Andy克莱门特但作为你可以看到,我试图获得一个在java ee环境中创建的实例(提示:java ee 6是其中一个标签),执行中的新行为将不起作用。它会在se环境中工作。有关如何在ee 6/7环境中执行此操作的任何线索? – Ikthiander